The hashchange event fires when a window's hash changes (see location.hash).

Syntax

window.onhashchange = funcRef;

or

<body onhashchange="funcRef();">

to overwrite any existing Event-Handlers.

In order to add an event-listener to an existing set of event-handlers use the function "addEventListener"

window.addEventListener("hashchange", funcRef, false);

 

Parameters

funcRef
A reference to a function.

Example

if ("onhashchange" in window) {
    //no alert
    console.log("The browser supports the hashchange event!");
}


function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;



// example

// Using the location.hash property to change the anchor part
function changeHash() {
    location.hash = (Math.random() > 0.5) ? "666" : "777";
}

// Alert some text if there has been changes to the anchor part
function HashHandler() {
    console.log("The Hash has changed!");
}

window.addEventListener("hashchange", HashHandler, false);


 

The hashchange event

The dispatched hashchange event has the following fields:

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.

Workaround for event.newURL and event.oldURL

//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;
	});
}());

Specifications

Specification Status Comment
HTML Living Standard
The definition of 'onhashchange' in that specification.
Living Standard  
HTML 5.1
The definition of 'GlobalEventHandlers' in that specification.
Recommendation  
HTML5
The definition of 'GlobalEventHandlers' in that specification.
Recommendation  

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung Internet
Basic supportChrome Full support 5Edge Full support YesFirefox Full support 3.6IE Full support 8Opera Full support 10Safari Full support 5WebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 11Safari iOS Full support 5Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown