HTML onhaschange Event Attribute


The event attribute onhaschange occurs when the anchor or hash part (starting with the # character) of the current URL changes.

An example of a hash part. Assuming we have the following URL: , the hash part will be '#part3'.

To trigger the onhashchange event, you must:

  • Change the anchor part by setting the location.hash or location.href property of the Location object in JavaScript.
  • Go to another label of the current page (using the Back or Forward buttons).
  • Click on the link leading to the anchor tag of the page.


<element onhaschange="script">


  • scriptThe name of the script to use when the event has been triggered.


<body onhashchange="myFunction()">
<p>Click on the button to change the anchor part of the current URL to #part7</p>
<button onclick="changePart()">Try it!</button>
<p id="demo"></p>
function changePart() {
    location.hash = "part7";
    var x = "Now the anchor part: " + location.hash;
    document.getElementById("demo").innerHTML = x;

function myFunction() {
    alert("The anchor part has changed!");

Supported Tags


Browser Support

Explorer Edge Chrome Firefox Opera Safari
Tablets / Mobile
Android Chrome Firefox Opera Safari Samsung