HTML event attribute onhashchange

The onhashchange attribute event is triggered when the URL hash is changed.

The URL hash is an anchor part starting with a '#' symbol of the current URL.

For the following URL

The anchor part of this URL is #myHash.

We can change the anchor hash by setting the location.hash or location.href property from the Location Object.

What's new in HTML5

The onhashchange attribute is new in HTML5.


<element onhashchange="script or Javascript function name">

Supported Tags


Browser compatibility

onhashchange Yes 8.0 Yes Yes Yes


<!DOCTYPE html>
<body onhashchange="myFunction()">
<!--from ww w.j a v  a 2  s .c  om-->
<button onclick="changePart()">Click me to change the hash</button>

function changePart() {
    location.hash = "part5";
    alert("The anchor part is now: " + location.hash);
function myFunction() {
    alert("The anchor part has changed!");


Click to view the demo