Change hash without triggering hashchange event

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; } 
+43
javascript jquery
Nov 05 2018-10-11
source share
2 answers

You may have a function like this:

 function updateHash(newHash){ ... oldHash = newHash } 

then in your setTimeOut you need to do

 function(){ if(oldHash != currenHash){ updateHash(currenHash); } } 

So, now you can call the update hash manually, and this event will not be triggered by the event. You can also have more options in updateHash to do other things.

By the way, have you looked at the jquery history plugin? http://tkyk.github.com/jquery-history-plugin/
+5
Nov 05 2018-10-11T00:
source share

You can use history.replaceState and add a hash to replace the current URI without triggering the hashchange event:

 var newHash = 'test'; history.replaceState(null, null, document.location.pathname + '#' + newHash); 

JSFiddle example

+5
Jul 06 '17 at 13:55 on
source share



All Articles