Computer >> Computer tutorials >  >> Programming >> HTML

Execute a script when there have been changes to the anchor part of the URL in HTML?


Use the onhashchange attribute to execute a script when anchor part of the URL is changed in HTML.

Example

You can try to run the following code to implement onhashchange attribute −

<!DOCTYPE html>
<html>
   <body onhashchange = "display()">
      <p>Change the anchor part</p>
      <button onclick = "change()">Change</button>
      <p id = "test"></p>
      <script>
         function change() {
            location.hash = "part2";
            var a = "Anchor part now- " + location.hash;
            document.getElementById("test").innerHTML = a;
         }
         function display() {
            alert("The anchor part has changed!");
         }
      </script>
   </body>
</html>