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!