Open In App

HTML DOM HashChangeEvent

The HashChangeEvent in HTML DOM is an interface between the events that are triggered when the hash of the URL has been changed. The anchor part of the URL follows the # symbol.

Supported Tags 



Properties/Methods: 

Syntax:  



event.newURL

Syntax:  

event.oldURL

onhashchange Event: This property occurred when there have been changes to the hash of the current URL. 

Syntax: 

<element onhashchange = "script">

Example 1: In this example, we will use the DOM HashChangeEvent.




<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM HashChangeEvent
    </title>
</head>
   
<body onhashchange="GFG(event)">
    <h3>
        Click on the button to see the change in URL
    </h3>
    <button onclick="geeks()">
        Change
    </button>
    <p id="sudo"></p>
    <script>
        // Use location.hash property to
        // change the anchor part
        function geeks() {
            location.hash = "#GeeksforGeeks";
        }
        function GFG() {
            document.getElementById("sudo").innerHTML
                = "<h3>Previous URL: " + event.oldURL
                + "<h3>New URL: " + event.newURL;
        }
    </script>
</body>
</html>

Output: 

 

Example 2:  In this example, we will use the DOM HashChangeEvent.




<!DOCTYPE html>
<html>
<head>
    <title>
        HTML DOM HashChangeEvent
    </title>
</head>
   
<body onhashchange="GFG()">
    <h4>Click the button</h4>
    <button onclick="geeks()">
        Click Here!
    </button>
    <p id="sudo"></p>
    <script>
        function geeks() {
            location.hash = "#GeeksforGeeks";
            let x = location.hash;
            document.getElementById("sudo").innerHTML
                = "The new anchor part is: " + x;
        }
        function GFG() {
            alert("The hash has been changed!");
        }
    </script>
</body>
</html>

Output: 

 

Supported Browsers: The browser supported by DOM HashChangeEvent property are listed below: 


Article Tags :