HTML onhashchange Event Attribute


The HTML onhashchange event attribute is triggered when there is a change in the anchor part of the URL in an HTML document.

Syntax

Following is the syntax −

<tagname onhashchange=”script”></tagname>

Let us see an example of HTML onhashchange event attribute−

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #FBAB7E;
      background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      color: #fff;
      height: 2rem;
      padding: 8px 10px;
   }
</style>
</head>
<body onhashchange="hashChange()">
<h1>HTML onhashchange Event Attribute Demo</h1>
<button class="btn" onclick="change()">Set Hash</button>
<p class="msg"></p>
<script>
   function change() {
      location.hash = "newHashPart";
      document.querySelector('.msg').innerHTML = 'The hash part of the URL is: ' + location.hash;
   }
   function hashChange() {
      document.body.style.background = 'lightblue';
   }
</script>
</body>
</html>

Output

Click on “Set Hash” button to set a new hash to current URL and observe how onhashchange event attribute works:

Updated on: 27-Sep-2019

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements