The HTML onhashchange attribute is an event handler that triggers the execution of a script when the anchor part of the current URL (the part of the URL that starts with the '#' symbol) changes.
Definition and Usage
➔ The anchor part of the current URL begins with the '#' symbol. For example "http://www.example.com/sample.html#demo", The anchor part of this URL is #demo.
➔ This event is typically used for dynamic web applications to update content without the need for a full page reload.
➔ This event is usually attached to the <body> element or the window object.
Syntax
//In HTML
<body onhashchange="myFunction()">
// In Javascript object
bodyobject.onhashchange =function() {myHandler()};
// In Javascript object
bodyobject.onhashchange = (event) => { };
// Using EventListener
bodyobject.addEventListener("hashchange", (event) => { });
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onhashchange | <body> |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML onhashchange Attribute Example</title>
<meta charset="utf-8" />
<style>
input[type="button"] {
width: 150px;
height: 50px;
background-color: #2e3e4e;
font-size: 14pt;
color: white;
border-radius: 5px;
margin-left: 140px;
}
input[type="button"]:hover {
background-color: #1d2d3d;
color: white;
}
</style>
</head>
<body>
<h2>HTML onhashchange Attribute Example</h2>
<p>Click the button to change the anchor part of the URL and start the event.</p>
<input type="button" value="Submit" id="button" onclick="changeAnchorPart()">
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
location.hash = "hello";
document.querySelector("body").onhashchange = function () { myFunction(this) };
function changeAnchorPart() {
document.getElementById("demo1").innerHTML = "URL: " + location.href;
document.getElementById("demo2").innerHTML = "Anchor part before: " + location.hash;
location.hash = "demo";
document.getElementById("demo3").innerHTML = "Anchor part change to : " + location.hash;
}
function myFunction(p) {
alert("The anchor part has changed to : " + p.location.hash);
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.