The HashChangeEvent event is fired when the fragment identifier of the URL has changed (the part of the URL that follows the # symbol, including the # symbol).
HashChangeEvent.newURL Read only HashChangeEvent.oldURL Read only window.onhashchange = funcRef;
or
<body onhashchange="funcRef();">
or
window.addEventListener("hashchange", funcRef, false);
funcReffunction locationHashChanged() {
if (location.hash === "#somecoolfeature") {
somecoolfeature();
}
}
window.addEventListener("hashchange", locationHashChanged);
There are several fallback scripts listed on this page. Basically those scripts check the location.hash at a regular interval. Here is a version that allows only one handler to be bound to the <code>window.onhashchange</code> property:
(function(window) {
// exit if the browser implements that event
if ( "onhashchange" in window.document.body ) { return; }
var location = window.location,
oldURL = location.href,
oldHash = location.hash;
// check the location hash on a 100ms interval
setInterval(function() {
var newURL = location.href,
newHash = location.hash;
// if the hash has changed and a handler has been bound...
if ( newHash != oldHash && typeof window.onhashchange === "function" ) {
// execute the handler
window.onhashchange({
type: "hashchange",
oldURL: oldURL,
newURL: newURL
});
oldURL = newURL;
oldHash = newHash;
}
}, 100);
})(window);
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'HashChangeEvent' in that specification. | Living Standard | Initial definition |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | 5 | Yes | 3.6 | 8 | 10.6 | 5 |
oldURL |
Yes | ? | 6 | No | Yes | ? |
newURL |
Yes | ? | 6 | No | Yes | ? |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | 4 | 11.0 | 5 | ? |
oldURL |
Yes | Yes | ? | Yes | Yes | ? | ? |
newURL |
Yes | Yes | ? | Yes | Yes | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent