Javascript DOM HashChangeEvent newURL Property

Introduction

When the hash has been changed, get the URL we are navigating to:

event.newURL;

Click the button to change the anchor part (hash) of the current URL to #part5.

The oldURL property returns the URL of the document we navigated away from.

The newURL property returns the URL we are navigating to.

View in separate window

<!DOCTYPE html>
<html>
<body onhashchange="myFunction(event)">
<button onclick="changePart()">Test</button>
<p id="demo"></p>
<script>
// Using the location.hash property to change the anchor part
function changePart() {//from ww w .  jav a 2s. c om
  location.hash = "part5";
}

function myFunction() {
  document.getElementById("demo").innerHTML = "Previous URL: " + event.oldURL
  + "<br>New URL: " + event.newURL;
}
</script>

</body>
</html>

The newURL property returns the URL of the document, after the hash has been changed.

This is the URL that was navigated to.

To get the URL that was navigated away from, use the oldURL property.

This property is read-only.

To set or return the hash of a URL, use the location.hash property.




PreviousNext

Related