The WindowEventHandlers.onhashchange
property of the WindowEventHandlers
mixin is the event handler for processing hashchange
events.
The hashchange
event fires when a window's hash changes (see Window.location
and HTMLAnchorElement.hash
).
Using an event handler:
window.onhashchange = funcRef;
Using an HTML event handler:
<body onhashchange="funcRef();">
Using an event listener:
To add an event listener, use addEventListener()
:
window.addEventListener("hashchange", funcRef, false);
funcRef
A reference to a function.
This example uses an event handler (window.onhashchange
) to check the new hash value whenever it changes. If it equals #cool-feature
, the script logs a message to the console.
function locationHashChanged() { if (location.hash === '#cool-feature') { console.log("You're visiting a cool feature!"); } } window.onhashchange = locationHashChanged;
This example uses an event listener to log a notification whenever the hash has changed.
function hashHandler() { console.log('The hash has changed!'); } window.addEventListener('hashchange', hashHandler, false);
This function sets a new hash dynamically, setting it randomly to one of two values.
function changeHash() { location.hash = (Math.random() > 0.5) ? 'location1' : 'location2'; }
The dispatched hashchange
event has the following properties:
Field | Type | Description |
---|---|---|
newURL | DOMString | The new URL to which the window is navigating. |
oldURL | DOMString | The previous URL from which the window was navigated. |
// Let this snippet run before your hashchange event binding code if (!window.HashChangeEvent)(function(){ var lastURL = document.URL; window.addEventListener("hashchange", function(event){ Object.defineProperty(event, "oldURL", {enumerable:true,configurable:true,value:lastURL}); Object.defineProperty(event, "newURL", {enumerable:true,configurable:true,value:document.URL}); lastURL = document.URL; }); }());
Specification |
---|
HTML Standard (HTML) # handler-window-onhashchange |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
onhashchange |
5 |
12 |
3.6 |
8 |
10 |
5 |
≤37 |
18 |
4 |
10.1 |
5 |
1.0 |
hashchange
event history.pushState()
and history.replaceState()
methodsWindowEventHandlers.onpopstate
HTMLAnchorElement.hash
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange