js detect hash change

How to Detect Hash Change in JavaScript

If you're working on a website that uses hash-based navigation, you may need to detect when the hash changes in order to update the page content. Fortunately, JavaScript provides a built-in way to do this using the hashchange event.

Method 1: Using the hashchange Event

The hashchange event fires whenever the hash part of the URL changes. To listen for this event, you can use the window.addEventListener() method:

window.addEventListener('hashchange', function() {
  // Code to execute when the hash changes
});

In the above code, we're passing an anonymous function as the second argument to window.addEventListener(). This function will be called whenever the hashchange event fires. Inside the function, you can put any code that you want to execute when the hash changes.

Method 2: Using setInterval()

If you need more control over when your code executes, you can use setInterval() to periodically check the URL hash:

// Save the current hash value
var currentHash = window.location.hash;

// Set up a function to check the hash value periodically
var checkHash = setInterval(function() {
  if (window.location.hash !== currentHash) {
    // Code to execute when the hash changes
    currentHash = window.location.hash;
  }
}, 100); // Check every 100 milliseconds

In this example, we're using setInterval() to check the URL hash every 100 milliseconds. If the hash has changed since the last check, we execute our code and update the currentHash variable to the new value.

Method 3: Using the onhashchange Property

Finally, you can also use the onhashchange property to detect hash changes:

// Save the current hash value
var currentHash = window.location.hash;

// Set up a function to execute when the hash changes
window.onhashchange = function() {
  // Code to execute when the hash changes
  currentHash = window.location.hash;
};

In this example, we're assigning a function to the onhashchange property of the window object. This function will be called whenever the hash changes, and it can access the new hash value using window.location.hash.

Conclusion

These are three different ways to detect hash changes in JavaScript. Which one you use depends on your specific needs and preferences. Regardless of which method you choose, make sure to test your code thoroughly to ensure that it works as expected in all browsers.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe