Handle URL fragment identifier (anchor) change event in Javascript

JavascriptEvent HandlingDom EventsFragment IdentifierHashchange

Javascript Problem Overview


How can I write the Javascript callback code that will be executed on any changes in the URL fragment identifier (anchor)?

For example from http://example.com#a to http://example.com#b

Javascript Solutions


Solution 1 - Javascript

Google Custom Search Engines use a timer to check the hash against a previous value, whilst the child iframe on a seperate domain updates the parent's location hash to contain the size of the iframe document's body. When the timer catches the change, the parent can resize the iframe to match that of the body so that scrollbars aren't displayed.

Something like the following achieves the same:

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
        storedHash = window.location.hash;
        hashChanged(storedHash);
    }
}, 100); // Google uses 100ms intervals I think, might be lower

Google Chrome 5, Safari 5, Opera 10.60, Firefox 3.6 and Internet Explorer 8 all support the hashchange event:

if ("onhashchange" in window) // does the browser support the hashchange event?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }

and putting it together:

if ("onhashchange" in window) { // event supported?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }
}
else { // event not supported:
    var storedHash = window.location.hash;
    window.setInterval(function () {
        if (window.location.hash != storedHash) {
            storedHash = window.location.hash;
            hashChanged(storedHash);
        }
    }, 100);
}

jQuery also has a plugin that will check for the hashchange event and provide its own if necessary - http://benalman.com/projects/jquery-hashchange-plugin/.

EDIT: Updated browser support (again).

Solution 2 - Javascript

An event listener can be added for the hashchange event, which will fire whenever the fragment identifier changes:

window.addEventListener('hashchange', function() {
  // Perform action
  // [...]
})

I would recommend this approach instead of overwriting window.onhashchange, otherwise you will block the event for other plugins.

Looking at the global browser usage today, a fallback is longer needed, as modern browsers support this event.

Solution 3 - Javascript

From what I see in other SO questions, the only workable cross-browser solution is a timer. Check out this question for example.

Solution 4 - Javascript

setInterval() is only universal solution for now. But there are some light in the future in form of hashchange event

Solution 5 - Javascript

(Just for the record.) The YUI3 "hashchange" synthetic event does more or less the same thing as the accepted answer

YUI().use('history-hash', function (Y) {
  Y.on('hashchange', function (e) {
    // Handle hashchange events on the current window.
  }, Y.config.win);
});

Solution 6 - Javascript

Here's a simple way that worked just fine for me with jQuery. I've added a animation to scroll to the anchor element aswell:

$(window).on('hashchange', function(e){
     var origEvent = e.originalEvent;
		 var elementToBeClicked = $('a[href^="'+window.location.hash+'"]').click();  
		$([document.documentElement, document.body]).animate({
        scrollTop: 200
    }, 100);
});

Hope it works for you.

Solution 7 - Javascript

You can get more info from this

Mutation event types

> The mutation event module is designed > to allow notification of any changes > to the structure of a document, > including attr and text modifications.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBogdan GusievView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptFabian von EllertsView Answer on Stackoverflow
Solution 3 - JavascriptPekkaView Answer on Stackoverflow
Solution 4 - JavascriptNilColorView Answer on Stackoverflow
Solution 5 - JavascriptmjhmView Answer on Stackoverflow
Solution 6 - JavascriptJoão Casas FernandesView Answer on Stackoverflow
Solution 7 - JavascriptrahulView Answer on Stackoverflow