views:

919

answers:

5

How can I write the JavaScript callback code that will be executed on any changes in the URL anchor?

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

+1  A: 

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

Pekka
A: 

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.

rahul
+6  A: 

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, Firefox 3.6 and Internet Explorer 8 all support the hashchange event (come on, Opera!):

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.

Andy E
+1  A: 

My solution (for Struts2)

Trick
+1  A: 

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

NilColor