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};

In JavaScript, the addEventListener() function is used.

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>
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.