onhashchange
The onhashchange event is triggered when there are changes to the anchor portion (starting with the '#' symbol) of the current URL.
onhashchange event
The onhashchange
event handler is triggered when there is a change in the input state of a form element. This event is useful for detecting updates in user input or changes in selection.
Syntax
In HTML
index.html
<element onhashchange="myScript">
In JS
script.js
object.onhashchange = function(){myScript};
addEventListener()
function is used. In JavaScript, the
script.js
object.addEventListener("hashchange", myScript);
Example
::event-onhashchange
::
<!DOCTYPE html>
<html>
<body onhashchange="myFunction()">
<p>Click the button to change the anchor part of the current URL to #part5</p>
<button onclick="changePart()">Try it</button>
<p id="demo"></p>
</body>
</html>
// Using the location.hash property to change the anchor part
function changePart() {
location.hash = "part5";
var x = location.hash;
document.getElementById("demo").innerHTML = "The anchor part is now: " + x;
}
// Alert some text if there has been changes to the anchor part
function myFunction() {
alert("The anchor part has changed!");
}
An alert will appear whenever the state of the checkbox is changed.
Value
Conclusion
The onhashchange
event is a powerful tool for detecting changes in the URL’s fragment identifier. It enables developers to react to URL’s #
updates without requiring a page reload, improving the user experience by enabling dynamic content changes based on the URL.