Search code examples
javascriptjquerydom-eventspredicatefragment-identifier

Prevent window.onhashchange from executing when hash is set via JavaScript


I use the window.onhashchange function to execute code when the User changes the hash of the page:

window.onhashchange = function() { /* do something */ };

In some functions I also set the hash via JavaScript:

window.location.hash = "#abc";

I want to prevent the onhashchange event from firing when I set the hash via JavaScript.

What I have tried so far:

var currently_setting_hash = false;

window.onhashchange = function() {
  if (currently_setting_hash)
    return;
 //...
}

currently_setting_hash = true;
window.location.hash = "#abc";
currently_setting_hash = false;

That didn't work because the event is fired with a delay, so the code will first set the hash, then set currently_setting_hash to false and then execute the onhashchange event.

Any ideas how this could be accomplished? Or maybe is there a way to detect if the hash was set by the user or via JavaScript?


Solution

  • You could reset the variable from the event handler itself:

    var currently_setting_hash = false;
    
    $(window).on("hashchange", function() {
        if (currently_setting_hash) {
            currently_setting_hash = false;
            return;
        }
    
        currently_setting_hash = false;
        //...
    });
    
    currently_setting_hash = true;
    window.location.hash = "#abc";