583

I am using Ajax and hash for navigation.

Is there a way to check if the window.location.hash changed like this?

http://example.com/blah#123 to http://example.com/blah#456

It works if I check it when the document loads.

But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).

It shows inside the address box, but I can't catch it with JavaScript.

isherwood
  • 58,414
  • 16
  • 114
  • 157
MilMike
  • 12,571
  • 15
  • 65
  • 82
  • 6
    Checkout this jquery plugin: https://github.com/cowboy/jquery-hashchange – Xavi Jan 16 '11 at 22:38
  • 9
    [History.js](https://github.com/balupton/History.js) supports the HTML5 State Management Functionality (so you don't need to use hashes anymore!) and gracefully degrades it to HTML4 browsers using hashchanges. It supports jQuery, MooTools and Prototype out of the box. – balupton Jan 30 '11 at 13:58
  • @balupton, Actually we **still need to use hashes** to provide feedback to the user that a "new page" has been inserted into his history, unless you use URL-changing as feedback. – Pacerier Oct 12 '14 at 11:10
  • 1
    [Hasher]https://github.com/millermedeiros/hasher/ – Vishnoo Rath Jan 15 '15 at 14:42
  • hmm... I think you need moar [jQuery](http://stackoverflow.com/a/680865/6799340) – Penguin9 Feb 22 '17 at 14:42

11 Answers11

630

The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.


Update to keep this answer fresh:

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..
});

The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

vladkras
  • 16,483
  • 4
  • 45
  • 55
meandmycode
  • 17,067
  • 9
  • 48
  • 42
  • 29
    The latest Firefox build (3.6 alpha) also now supports the native hash changed event: https://developer.mozilla.org/en/DOM/window.onhashchange It is certainly worth doing a check for this event, but note that IE8 will tell you the event exists when it is running in IE7 compat mode.. sadly the event doesn't fire.. you'll need to check for the event and that the browser doesn't appear to be IE7.. sigh (or attempt to trigger the event with IE's fireEvent method). – meandmycode Aug 18 '09 at 13:50
  • 9
    At the time of writing, WebKit also fires `hashchange` event, while Safari (stable) does not yet. – jholster Apr 19 '10 at 21:19
  • dojo has the same thing: `dojo.subscribe("/dojo/hashchange", context, callback);` – nilskp Nov 17 '11 at 02:26
  • 54
    Just to add yet another update, the `hashchange` event is now widely supported: http://caniuse.com/#search=hash – Paystey Mar 12 '12 at 09:39
  • 23
    Am I the only one who thinks unsolicited jQuery answers are a pain? – Luc Aug 20 '12 at 00:06
  • Wasn't able to get this to work with jQuery 1.7. The plugin doesn't seem to have been updated in 2 years. – Lèse majesté Sep 25 '12 at 10:20
  • 2
    @Luc I totally agree with you! Why do all presume jQuery is always used! – mjs Jul 19 '13 at 19:24
  • @meandmycode can I detect change of (window.location) and handle it? (without jquery) – BergP Sep 13 '13 at 11:38
  • 7
    This answer is now deprecated –  Apr 11 '14 at 17:39
  • But how to know when the latest URL will be available? – VikkyB Oct 29 '14 at 21:12
  • @Jhawins what is the new answer? – SuperUberDuper Mar 19 '15 at 14:29
  • 1
    @SuperUberDuper the new answer is the one below this ([direct link](http://stackoverflow.com/a/681030/1596138)). In short the `hashchange` event is supported by all modern browsers and there is no need to use a jQuery "special event" plugin except for compatibility with older browsers. The code in this answer is fine though and should continue working. –  Mar 19 '15 at 15:25
  • Excellent answer, but could you maybe add some info on how to read the hashlocation from that event? – zrajm Feb 23 '17 at 17:40
  • @Luc 10 years later and nothing's changed, . These days if I ask a question, I just hide things like `if (typeof(jQuery)!=='undefined') throw Error('ENOUGH.')` in my snippets. Then I can legit claim that a jQuery answer causes an error in the code. – Jason C May 30 '22 at 21:02
307

HTML5 specifies a hashchange event. This event is now supported by all modern browsers. Support was added in the following browser versions:

  • Internet Explorer 8
  • Firefox 3.6
  • Chrome 5
  • Safari 5
  • Opera 10.6
Michael Martin-Smucker
  • 11,927
  • 7
  • 31
  • 36
Miles
  • 31,360
  • 7
  • 64
  • 74
  • 20
    Update: FF 5, Safari 5, and Chrome 12 support this event as of June 2011. – james.garriss Jun 29 '11 at 14:55
  • 2
    Here is the [CanIUse page for hashchange](http://caniuse.com/hashchange). Here is [hashchange on quirksmode](http://www.quirksmode.org/dom/events/#t011). IE support is buggy with respect to case sensitivity. – Tobu Oct 08 '11 at 10:42
  • 3
    @everybody, no need to keep appending to the answer in the comments section -- that's what the "Edit" button is for. :) – Michael Martin-Smucker Jun 15 '12 at 12:48
  • 19
    usage: `window.onhashchange = function() { doYourStuff(); }` – Christopher Aug 10 '15 at 15:31
  • 4
    MDN documentation of [hashchange event](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange). – lele1c Oct 09 '15 at 06:56
  • this doesn't seem to work with [history manipulation](http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page). there is [`window.onpopstate`](http://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate) but even that won't always work. – cregox May 14 '17 at 01:56
52

Note that in case of Internet Explorer 7 and Internet Explorer 9 the if statment will give true (for "onhashchange" in windows), but the window.onhashchange will never fire, so it's better to store hash and check it after every 100 millisecond whether it's changed or not for all versions of Internet Explorer.

    if (("onhashchange" in window) && !($.browser.msie)) {
         window.onhashchange = function () {
              alert(window.location.hash);
         }
         // Or $(window).bind( 'hashchange',function(e) {
         //       alert(window.location.hash);
         //   });
    }
    else {
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

EDIT - Since jQuery 1.9, $.browser.msie is not supported. Source: http://api.jquery.com/jquery.browser/

bonsaiviking
  • 5,825
  • 1
  • 20
  • 35
Khan Salahuddin
  • 585
  • 4
  • 4
15

I was using this in a React application to make the URL display different parameters depending what view the user was on.

I watched the hash parameter using

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

function doSomethingWithChangeFunction () {
    let urlParam = window.location.hash; // Get new hash value

    // ... Do something with new hash value
};

It works a treat. It works with forward and back browser buttons and also in the browser history.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sprose
  • 1,255
  • 1
  • 16
  • 20
14

There are a lot of tricks to deal with History and window.location.hash in IE browsers:

  • As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c.

  • Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page.

  • However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected.

  • If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)

I know this isn't a real response, but maybe IE-History notes are useful to somebody.

Sergio Cinos
  • 746
  • 6
  • 13
12

Firefox has had an onhashchange event since 3.6. See window.onhashchange.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
edfuh
  • 490
  • 5
  • 6
9

You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

The code will look like this:

window.location.watch(
    'hash',
    function(id,oldVal,newVal){
        console.log("the window's hash value has changed from "+oldval+" to "+newVal);
    }
);

Then you can test it:

var myHashLink = "home";
window.location = window.location + "#" + myHashLink;

And of course that will trigger your observer function.

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
  • Better use: window.location.href instead of window.location. – Codebeat May 10 '12 at 21:01
  • 3
    He's watching window.location.hash, not window.location. – undefined Sep 25 '12 at 23:56
  • 1
    @BrianMortenson: according to the docs (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/watch) you must apply `watch` to the object that owns the property that is changing and you want to observe it. – gion_13 Sep 26 '12 at 07:41
  • @gion_13 Yes, that's exactly what I was trying to point out. By 'He' I meant you, and it was directed at Erwinus' comment. I should have been more clear. Thanks for your clarifying comment. – undefined Sep 26 '12 at 16:05
1

I've been using path.js for my client side routing. I've found it to be quite succinct and lightweight (it's also been published to NPM too), and makes use of hash based navigation.

path.js NPM

path.js GitHub

Tom
  • 59
  • 2
  • 10
1

Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

Community
  • 1
  • 1
balupton
  • 47,113
  • 32
  • 131
  • 182
1
var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    }
    return false;
}
var RunTabs = setInterval(TrackHash, 200);

That's it... now, anytime you hit your back or forward buttons, the page will reload as per the new hash value.

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
batman
  • 59
  • 2
  • 10
0

A short and simple example:

Click on buttons to change the hash:

window.onhashchange = () => console.log(`Hash changed -> ${window.location.hash}`)
<button onclick="window.location.hash=Math.random()">hash to Math.Random</button>

<button onclick="window.location.hash='ABC'">Hash to ABC</button>

<button onclick="window.location.hash='XYZ'">Hash to XYZ</button>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GMKHussain
  • 3,342
  • 1
  • 21
  • 19