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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: