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

http://www.example.com/test.htm#myHash

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.

Syntax

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

Supported Tags

<body>




Browser compatibility

onhashchange Yes 8.0 Yes Yes Yes

Example

<!DOCTYPE html>
<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>

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

</body>
</html>

Click to view the demo