Question

overlay.onclick = function(e){
    e.preventDefault();
    window.location.hash = 'overlay';

    var close = function(){
        //do some stuff
        window.removeEventListener('hashchange', close);
    }

    window.addEventListener('hashchange', close, false);
}

Basically, as soon as I click the link, the hash is updated, and the close function is calling. The close function shouldn't be bound until AFTER the hash is changed. Why is the close function being called as soon as the listener is added, and how do I prevent it. Testing in Chrome, latest version.

Was it helpful?

Solution

I think it's because Javascript is synchronous, so when you set window.location.hash, the window.onhashchange method will not run until the onclick function currently running finishes. Does that make sense? So you set the .hash value, then bind a hashchange event...right after binding, the onhashchange event actually fires. So that in turn calls close. Try putting console.log statements throughout your code to see the order of execution.

UPDATE:

Here's a fiddle to demonstrate the order of things: http://jsfiddle.net/jmWDY/

Notice how the original onhashchange function is called first (after your function is finished), then your new binding (which is close). I hope this helped!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top