Window: hashchange event
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Thehashchange
event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the#
symbol).
This event does not fire when the hash is modified usinghistory.pushState()
orhistory.replaceState()
.
Syntax
Use the event name in methods likeaddEventListener()
, or set an event handler property.
addEventListener("hashchange", (event) => { })onhashchange = (event) => { }
Event type
AHashChangeEvent
. Inherits fromEvent
.
Event properties
HashChangeEvent.newURL
Read onlyA string representing the new URL the window is navigating to.
HashChangeEvent.oldURL
Read onlyA string representing the previous URL from which the window was navigated.
Event handler aliases
In addition to theWindow
interface, the event handler propertyonhashchange
is also available on the following targets:
Examples
You can use thehashchange
event in anaddEventListener
method:
window.addEventListener( "hashchange", () => { console.log("The hash has changed!"); }, false,);
Or use theonhashchange
event handler property:
function locationHashChanged() { if (location.hash === "#cool-feature") { console.log("You're visiting a cool feature!"); }}window.onhashchange = locationHashChanged;
Specifications
Specification |
---|
HTML # event-hashchange |
HTML # handler-window-onhashchange |
Browser compatibility
See also
popstate
event