onhashchange एट्रिब्यूट का उपयोग तब स्क्रिप्ट चलाने के लिए किया जाता है जब URL का एंकर पार्ट (हैश, # के बाद का भाग) बदलता है। यह सिंगल-पेज एप्लिकेशन्स (SPA), टैब नेविगेशन, इन-पेज एंकर नेविगेशन के लिए उपयोगी है।
उदाहरण
निम्न कोड से onhashchange एट्रिब्यूट लागू करें:
<!DOCTYPE html> <html>
<body onhashchange="display()">
<p>एंकर पार्ट बदलें</p>
<button onclick="change()">बदलें</button>
<p id="test"></p>
<script>
function change() {
location.hash = "part2";
var a = "एंकर पार्ट अब- " + location.hash;
document.getElementById("test").innerHTML = a;
}
function display() {
alert("एंकर पार्ट बदल गया!");
}
</script>
</body>
</html>
नोट: location.hash में # शामिल होता है। history.pushState() हैश नहीं बदलता (उसके लिए onpopstate उपयोग करें)।