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.
I think it’s because Javascript is synchronous, so when you set
window.location.hash, thewindow.onhashchangemethod will not run until theonclickfunction currently running finishes. Does that make sense? So you set the.hashvalue, then bind ahashchangeevent…right after binding, theonhashchangeevent actually fires. So that in turn callsclose. Try puttingconsole.logstatements 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
onhashchangefunction is called first (after your function is finished), then your new binding (which isclose). I hope this helped!