Explain Codes LogoExplain Codes Logo

How can I detect changes in location hash?

javascript
hashchange
ajax
performance
Anton ShumikhinbyAnton Shumikhin·Aug 9, 2024
TLDR
window.onhashchange = () => console.log(`Hash: ${location.hash}`);

This neat JavaScript snippet tracks URL hash changes using onhashchange. It's a key solution for navigation events in Single Page Applications (SPAs).

Modern Browsers' Hash Change Detection

Most modern browsers like IE8+, Firefox 3.6+, and Chrome 5+ offer native support for the hashchange event.

window.addEventListener('hashchange', function() { console.log('#Yikes, the hash changed!:', location.hash); });

Remember, this code might not work in a cave. So test it before running it in the wild.

Old Internet Explorer's Hash Change Detection

For browsers stuck in the past (read: IE7), you could use a polling mechanism and setInterval as a feature-detection strategy.

let storedHash = window.location.hash; setInterval(function() { if (window.location.hash !== storedHash) { storedHash = window.location.hash; console.log('The hash just changed while you blinked:', storedHash); } }, 100); // Do a Hash-o-Check every 100ms

This could drive your performance analyst nuts. But hey, it does wonders for our hash detection.

Hash Change Detection Boosted with jQuery

Here's some jQuery magic to make binding hashchange events simpler and ensuring cross-browser compatibility.

$(window).on('hashchange', function() { . console.log('#Hashmania, it changed again:', location.hash); });

Protip: $.browser.msie isn't supported after jQuery 1.9. So, Hulk-smash that out of your browser detection logic.

Advanced Hash Handling with reallysimplehistory

For advanced users or those dealing complex applications, reallysimplehistory can aid in hash tracking and history management.

// Using Really-Simple-History var rsh = require("reallysimplehistory"); rsh.onChange(function(newLocation) { console.log('Welcome to the Change Parade:', newLocation.hash); });

But remember, with great power comes great responsibility.

Deciphering Internet Explorer's Hash Quirks

For the fans of Internet Explorer's quirks, remember its unique way of handling location.hash. Especially when detailing with iframes and back button navigation.

Note: Accessing iframe.contentWindow.document could be restricted in some scenarios. Juggling document.domain might help get things rolling.

Stylish Navigation with Ajax and Hash

Combine hash changes with Ajax navigation to mimic a highway drive: smooth and exhilarating.

Using addEventListener, we can improve user experience and maintain application state across refreshes.

Security Shakedown

Remember, the hash part of the URL is exposed to the user which can be manipulated. So sanitize your hash input if it's part of any server-side operations.

Strategy for Handling High-Frequency Hash Changes

For applications with frequent hash changes, using a debounce or throttle function in the hashchange event can tremendously improve performance.

URI Encoding and Decoding for Hashes

If your hashes contain special characters or complex data, encode/decode them using encodeURIComponent and decodeURIComponent.

CSS Love for Hash Change

If you want to add some style to your hash change mechanism, CSS's :target pseudoclass lets you apply CSS styles based on the current hash.