JavaScript Reference ยท DOM: Events
The hashchange and popstate events
Reference for the hashchange and popstate events: detect URL fragment changes and back/forward navigation, read event.state and build a tiny client-side router.
Two events on window let a page react when the address changes without a full page load. hashchange fires when the URL fragment (the part after #) changes. popstate fires when the user moves through session history to a different entry, for example with the Back and Forward buttons or history.back().
They are the foundation of client-side routing. Fragment routing (#/about) needs only hashchange. Clean URLs (/about) use history.pushState() to change the address and popstate to handle going back.
window.addEventListener("hashchange", (event) => { console.log(event.oldURL, "->", event.newURL); }); window.addEventListener("popstate", (event) => { console.log("state:", event.state); });
Try it
Syntax
window.addEventListener("hashchange", listener); window.addEventListener("popstate", listener); window.onhashchange = listener; window.onpopstate = listener;
Event properties
| Event | Property | Description |
|---|---|---|
hashchange |
oldURL |
The full URL before the change. |
hashchange |
newURL |
The full URL after the change. |
popstate |
state |
A structured clone of the state object stored with the entry now active, or null. |
Both events fire on window, and neither is cancelable. hashchange has the type HashChangeEvent, and popstate has the type PopStateEvent.
Usage notes
pushState()andreplaceState()do not firepopstate. They change the entry without a notification, so update your UI yourself after calling them.popstatefires only when navigation moves to an existing entry.- Changing the hash fires both. Setting
location.hashor following a link like<a href="#about">creates a history entry and firespopstateand thenhashchange. - No event if the hash is set to the same value. Clicking a link to the current fragment does not fire
hashchange. popstateon first load. Older browsers firedpopstatewhen the page loaded. Modern ones do not, so call your render function once at startup, as in the router above.event.stateis a copy. It survives reloads on that entry but isnullfor entries your code did not create.- Fragments need no server setup. Clean URLs from
pushState()need the server to return your page for every route, or a reload gives a 404. - Scroll position. The browser may restore scroll on back navigation. Control it with
history.scrollRestoration. - Remember to read the hash safely.
location.hashincludes the#, and its content is user-controlled. Never put it intoinnerHTML.
Browser support
hashchange and popstate work in every current browser. The newer Navigation API (navigation.addEventListener("navigate", ...)) can replace both for single-page apps, but check a compatibility table before depending on it.
Related
historyโpushState(),replaceState(),back()locationโhash,searchandpathnameURL- DOMContentLoaded and load
- Lesson: URL and history