Javascript DOM onhashchange Event on window object

Introduction

To assign the "onhashchange" event to the window object:

window.onhashchange = myFunction;

This example demonstrates how to assign an "onhashchange" event to the window object.

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

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="changePart()">Test</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function changePart() {/*from   w  w  w.  j a  v  a2  s  . c o m*/
  location.hash = "part5";
  var x = location.hash;
  document.getElementById("demo").innerHTML = "The anchor part is now: " + x;
}

window.onhashchange = myFunction;

function myFunction() {
  document.getElementById("demo1").innerHTML = "The anchor part has changed!";
}
</script>

</body>
</html>



PreviousNext

Related