How to detect location hash changes in Javascript

Introduction

To detect the browser location hash changes in Javascript, there’s a web API event called hashchange. Which we can rely on to detect the change in the location hash.

How to use it?

There are two options to listen to the hashchange event:
  1. Attach the event (hashchange) to the addEventListener function, through any of the supported interfaces
  2. Call the event (onhashchange) on any of the supported interfaces.

Supported Interfaces:

  1. Window
  2. HTMLBodyElement
  3. HTMLFrameSetElement
  4. SVGSVGElement

Examples

1- Using addEventListener

To detect the hash change using the addEventListener method, we’re going to attach the event to it through the Window interface. As shown in the following example:

  window.addEventListener('hashchange', function (event) {
    console.log(event);
    alert('Hash change detected: ' + event.newURL);
  });

To be able to test it, we need to add a button that will update the browser location value once the user clicked on it, as shown below:

<button onclick="return changeLocationHash();">Change location hash</button>
<script>
   function changeLocationHash() {
     window.location = window.location + '#hash';
   }
</script>

Then once the browser location value is updated, the hashchange event handler will be executed, and we should be able to see the alert message.

How to detect location hash changes in Javascript
How to detect location hash changes in Javascript
Putting it together:
  <body>
    <button onclick="return changeLocationHash();">Change location hash</button>

    <script>
      function changeLocationHash() {
        window.location = window.location + '#hash';
      }

      // Option 1
      window.addEventListener('hashchange', function (event) {
        console.log(event);
        alert('Hash change detected: ' + event.newURL);
      });
    </script>
  </body>

2- Calling the event onhashchange

The 2nd option can be done, by calling the event onhashchange directly on any of the supported interfaces.

For example:
  <body>
    <button onclick="return changeLocationHash();">Change location hash</button>

    <script>
      function changeLocationHash() {
        window.location = window.location + '#hash2';
      }

      // Option 2
      window.onhashchange = function (event) {
        console.log(event);
        alert('Hash change detected: ' + event.newURL);
      };
    </script>
  </body>

As shown above in the example, we’ve attached the onhashchange directly to the Window interface, and assigned it a new function implementation, which will show an alert once the browser location hash changed.

Running the above code in the browser would results in the following:

How to detect location hash changes in Javascript
How to detect location hash changes in Javascript

Full source code:


That’s it for How to detect location hash changes in Javascript.

Photo from Unslpash.


Related Posts

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: