WindowEventHandlers.onhashchange

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

Syntax

JavaScript
window.onhashchange = funcRef;

or

JavaScript
<body onhashchange="funcRef();">

or

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

Parameters

funcRef
A reference to a function.

Example

JavaScript
if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

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

window.onhashchange = locationHashChanged;

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

JavaScript
//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
WHATWG HTML Living Standard
The definition of 'GlobalEventHandlers' in that specification.
Living Standard  
HTML5.1
The definition of 'GlobalEventHandlers' in that specification.
Working Draft  
HTML5
The definition of 'GlobalEventHandlers' in that specification.
Recommendation  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5.0 3.6 (1.9.2)

8.0

oldURL/newURL attributes are not supported.

10.6 5.0
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.2 1.0 (1.9.2) 9.0 11.0 5.0

License

© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-us/docs/web/api/windoweventhandlers/onhashchange

HTML-DOM Property Reference Référence WindowEventHandlers