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


In this article we are going to learn about execute a script when there have been changes to the anchor part of the URL in HTML.

The onhashchange attribute in HTML definition states that it activates once the anchor portion of the current URL has changed. The present URL's '#' sign introduces the anchor portion. A single value script for this attribute executes when the onhashchange event attribute is activated. This attribute only applies to the <body> tag.

Let’s dive into the following examples to understand more about executing a script when there have been changes to the anchor part of the URL in HTML.

Example

In the following examples we are using onhashchange attribute for <body> element.

<!DOCTYPE html>
<html>
<body onhashchange="mytutorial()">
   <p>Click To Change The Anchor</p>
   <button onclick="tutorial()">Try it</button><br><br><br>
   <p id="tutorial1"></p>
   <script>
      function tutorial() {
         location.hash = "Welcome";
         var x = "The anchor part is now: " + location.hash;
         document.getElementById("tutorial1").innerHTML = x;
      }
      function mytutorial() {
         alert("Changed The Anchor Part");
      }
   </script>
</body>
</html>

When the script gets executed, it will generate an output displaying the text along with a click button on the webpage.

When the user tries to click the button, the event gets triggered and changes the anchor part and displays an alert on the webpage.

Using addEventListener() method

The EventTarget interface's addEventListener() method creates a function that will be called each time the provided event is sent to the target. Common targets include Element or its descendants, Document, and Window, although any object that supports events may serve as a target (such as XMLHttpRequest ).

Example

In the following we are using onhashchange attribute along with the addEventListener() method.

<!DOCTYPE html>
<html>
<body>
   <p>Click Button To Change Anchor Part</p>
   <button onclick="tutorial()">Click</button><br><br><br>
   <p id="tutorial1"></p>
   <script>
      function tutorial() {
         location.hash = "TUTORIALSPOINT";
         var x = location.hash;
         document.getElementById("tutorial1").innerHTML = "The anchor part is now: " + x;
      }
      window.addEventListener("hashchange", mytutorial);
      function mytutorial() {
         alert("Anchor Part Has Changed!");
      }
   </script>
</body>
</html>

On running the above script, the output window pops up and displays the text along with the button on the webpage.

If the user tries to click the button, the event gets triggered and changes the anchor part and displays an alert on the webpage.

Updated on: 16-Dec-2022

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements