18

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?

qwertymk
  • 34,200
  • 28
  • 121
  • 184

1 Answers1

21

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.

Starx
  • 77,474
  • 47
  • 185
  • 261
James Kyburz
  • 13,775
  • 1
  • 32
  • 33
  • I don't fully understand the logic of the quote. E.g. if one programatically pushes a state via `history.pushState()`, the history will be changed as well, but no `'popstate'` event is fired. One could argue, that's because there it's not needed, as it's changed by the programmer. But in contrast the `'popstate'` event is fired when the hash is changed even in the case where this is done programmatically. (tested with Firefox 104) – Sebastian Sep 15 '22 at 14:01