HTML DOM HashChangeEvent


The HTML DOM HashChangeEvent is a type of interface used for representing those events that fire whenever the # part of the URL has been modified.

Properties

Following are the properties for the HashChangeEvent −

PropertyDescription
newURLTo return the document URL after the hash has been modified.
oldURLTo returns the document URL before the hash was changed

Syntax

Following is the syntax for HashChangeEvent.

event.eventProperty

Here, eventProperty is one of the above two properties.

Example

Let us look at an example for the HashChangeEvent.

<!DOCTYPE html>
<html>
<body onhashchange="showChange(event)">
<h1>HashChangeEvent example</h1>
<p>Change the hash by clicking the below button</p>
<button onclick="changeHash()">CHANGE</button>
<p id="Sample"></p>
<script>
   function changeHash() {
      location.hash = "NEWHASH";
   }
   function showChange() {
      document.getElementById("Sample").innerHTML = "The url has been changed from " + event.oldURL + " to " + event.newURL;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example

We have created a button CHANGE that will execute the changeHash() method when clicked by the user.

<button onclick="changeHash()">CHANGE</button>

The changeHash() method changes the hash property of the location object to “NEWHASH”. The location object contains information about our URL −

function changeHash() {
   location.hash = "NEWHASH";
}

As soon as the hash is changed, the onhashchange event handler associated with the body tag fires and passes the haschange event as object to function showChange() −

<body onhashchange="showChange(event)">

The showChange() method uses the hashchange event received to display the oldURL property and newURL property in the paragraph element with id “sample” −

function showChange() {
   document.getElementById("Sample").innerHTML = "The url has been changed from " + event.oldURL + " to " + event.newURL;
}
raja
Published on 09-Aug-2019 12:29:05
Advertisements