I use a hash to dynamically load content. To make the back button, I commit hash changes. However, sometimes I need to change the hash without starting the hash change function (for example, when the page was redirected to the server side, and I need to update the hash after the content is returned.)
The best solution I came up with is to cancel the hashchange event, make the changes, and then reinstall it. However, since this happens asynchronously, I find that it jumps too fast and still catches the hash change.
My solution at the moment is very bad: forwarding to setTimeout. Anyone have a better idea?
$(window).unbind( 'hashchange', hashChanged); window.location.hash = "!" + url; setTimeout(function(){ $(window).bind( 'hashchange', hashChanged); }, 100);
Edit:
Amir Raminfar's suggestion prompted me a solution that does not require a timeout. I added a class variable
_ignoreHashChange = false;
When I want to quietly change the hash, I do this:
_ignoreHashChange = true; window.location.hash = "!" + url;
and the hash change event does the following:
function hashChanged(event){ if(_ignoreHashChange === false){ url = window.location.hash.slice(2); fetchContent(url); } _ignoreHashChange = false; }
javascript jquery
SystemicPlural Nov 05 2018-10-11 14:17
source share