HTML onhaschange Event Attribute

Description

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: http://www.example.com/test.php#part3 , 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.

Syntax

<element onhaschange="script">

Values

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

Example

<!DOCTYPE HTML>
<html>
<head>
</head>
<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>
<script>
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!");
}
</script>
</body>
</html>

Supported Tags

<body>

Browser Support

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