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

HTMLWeb DevelopmentFront End Technology

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


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

<!DOCTYPE html>
   <body onhashchange = "display()">
      <p>Change the anchor part</p>
      <button onclick = "change()">Change</button>
      <p id = "test"></p>
         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!");
Updated on 03-Mar-2020 12:23:09