Since the event is delayed, there is a chance of events occurring in a different order than you expect (for example, imagine that the user changes the URL in other ways, either immediately before or after your code). It is important to make sure that you do not become inconsistent in believing that this is your event. So I have a suggestion (based on your code and Adam Bubela):
var expectedHash; window.onhashchange = function () { if (window.location.hash === expectedHash) { return; } expectedHash = window.location.hash;
This code will suppress the change handler only if the change is to the expected value . (Assigning inside onhashchange ensures that the handler also works if the hash temporarily moves to a different value, which, I believe, is more correct than the alternative.)
The third helper function canonicalizeHashValue is only needed for precision if you specify a non-canonical value, for example. changeHash('foo') instead of changeHash('#foo') .
source share