HTML onhashchange 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
Browser Support
The following information will show you the current browser support for the HTML onhashchange event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 27th December 2025
