HTML onhaschange Event Attribute
Description
The onhashchange
HTML event attribute is triggered when the anchor part of the current URL changes. The anchor part is the part of the URL that starts with the #
symbol. For example, in the URL https://www.example.com/test.htm#part2
, the anchor part is #part2
.
The onhashchange
event can be used to update the page content or to perform other actions when the user navigates to a different bookmark on the same page, or when they use the back and forward buttons to navigate to a different page with the same anchor part.
To use the onhashchange
event, you simply add the attribute to the <body>
element of your HTML document, and then assign a JavaScript function to the attribute value. The function will be executed whenever the anchor part of the URL changes.
For example, the following HTML code would execute the myFunction()
function whenever the anchor part of the URL changes:
<body onhashchange="myFunction()">
...
</body>
In the myFunction()
function, you can use the location.hash
property to get the current anchor part of the URL. You can then use this information to update the page content or to perform other actions.
Here is an example of a myFunction()
function that updates the page content to display the current anchor part of the URL:
function myFunction() {
var anchorPart = location.hash;
document.getElementById("anchorPart").innerHTML = anchorPart;
}
In this example, the anchorPart
variable is assigned the current anchor part of the URL. The innerHTML
property of the anchorPart
element is then set to the value of the anchorPart
variable. This will cause the anchorPart
element to display the current anchor part of the URL.
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("EXAMPLE: The anchor part has changed!");
}
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onhaschange
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023