91

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

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Bogdan Gusiev
  • 7,447
  • 14
  • 59
  • 76

6 Answers6

129

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).

Andy E
  • 311,406
  • 78
  • 462
  • 440
  • for completeness, add `var storedHash = window.location.hash;` to the putting-it-together summary block. Btw: Nowadays this is called polyfill I think. – Frank Nocke Mar 31 '13 at 14:58
  • 1
    Nowadays you can listen to the `hashChange` on `window` http://stackoverflow.com/questions/6390341/how-to-detect-url-change – Timo Huovinen Oct 08 '13 at 19:55
  • @AndyE I did read the answer, I missed the small note, and I have never seen events that look like `hashChanged(storedHash);` – Timo Huovinen Oct 09 '13 at 08:39
  • 1
    @TimoHuovinen: `hashChanged`, in this case, is intended to be a function implemented by a developer using this code. The answer here just demonstrates how one may monitor the hash for changes where the `onhashchange` event is not available, and combines the event-based and timer-based approaches to provide a universal solution. My point is that the answer that you linked to adds absolutely nothing to the answer here ;-). They provide the same basic information, even the link to Ben Alman's jQuery plugin. The only difference is that I provided a pure JS solution in my answer. – Andy E Oct 09 '13 at 09:25
  • @AndyE ok, wasn't aware of the requirement to implement that function, thank you for clarifying – Timo Huovinen Oct 09 '13 at 10:01
  • 1
    I was looking for some lightweight JS router, but this did the job nicely. Also eliminated all dependencies :) – gskema Jun 22 '14 at 14:04
7

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

window.addEventListener('hashchange', function() {
...
})

Looking at the global browser usage today, a fallback is not needed anymore.

Fabian von Ellerts
  • 3,261
  • 28
  • 31
3

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

Community
  • 1
  • 1
Pekka
  • 418,526
  • 129
  • 929
  • 1,058
3

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

NilColor
  • 3,342
  • 2
  • 27
  • 44
  • FYI: `onhashchange` event's [documentation at Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange) –  May 28 '15 at 05:15
2

(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);
});
mjhm
  • 15,731
  • 9
  • 40
  • 55
0

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
  • 174,563
  • 47
  • 223
  • 254