qwertymk qwertymk - 1 year ago 92
Javascript Question

hashchange firing popstate

Here's what I'm working with



Code:

<a href="#" onclick="window.onpopstate = function() { alert('pop'); };
return false; ">set up window.onpopstate
</a><br>
<a href="#somehash2">change hash</a>
<div onclick="alert(location.href);">show location.href</div>‚Äč


Why does clicking the
change hash
link fire the popstate, shouldn't it only be fired if I click the
change hash
link then click back?

Answer Source

The reason window.onpopstate fires are not because of a change to the hash. It's because the history has been changed when you click on the anchor tag.

From https://developer.mozilla.org/en/DOM/window.onpopstate :

A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download