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.


Following is the syntax −

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

Let us see an example of HTML onhashchange event attribute−


 Live Demo

<!DOCTYPE html>
   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;
<body onhashchange="hashChange()">
<h1>HTML onhashchange Event Attribute Demo</h1>
<button class="btn" onclick="change()">Set Hash</button>
<p class="msg"></p>
   function change() {
      location.hash = "newHashPart";
      document.querySelector('.msg').innerHTML = 'The hash part of the URL is: ' + location.hash;
   function hashChange() { = 'lightblue';


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


Kickstart Your Career

Get certified by completing the course

Get Started