Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Preli Avatar asked Nov 05 '12 14:11

Preli


1 Answers

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";
like image 143
Frédéric Hamidi Avatar answered Sep 27 '22 16:09

Frédéric Hamidi