How can I detect changes in location hash?
Solution 1
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.
Solution 2
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
Solution 3
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/
Solution 4
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.
Solution 5
Firefox has had an onhashchange event since 3.6. See window.onhashchange.
MilMike
<?php echo "hi"; ?> Hi, my name is Mike. I love to code. Started to code over 20 years ago. I feel at home using a bride spectrum of technologies. Currently I work full time as a web developer in Germany working on PHP/JS projects, but I also developed desktop applications for Windows. Most of the time I work as a backend developer but I also love to work with frontend. If you want to know more about me, just go to my small website or follow me on instagra: My Website Instagram
Updated on July 08, 2022Comments
-
MilMike almost 2 years
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.
-
Xavi over 13 yearsCheckout this jquery plugin: github.com/cowboy/jquery-hashchange
-
balupton over 13 yearsHistory.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.
-
Pacerier over 9 years@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.
-
Vishnoo Rath over 9 years[Hasher]github.com/millermedeiros/hasher
-
Penguin9 over 7 yearshmm... I think you need moar jQuery
-
-
meandmycode almost 15 yearsThe latest Firefox build (3.6 alpha) also now supports the native hash changed event: 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).
-
jholster about 14 yearsAt the time of writing, WebKit also fires
hashchange
event, while Safari (stable) does not yet. -
james.garriss almost 13 yearsUpdate: FF 5, Safari 5, and Chrome 12 support this event as of June 2011.
-
Tobu over 12 yearsHere is the CanIUse page for hashchange. Here is hashchange on quirksmode. IE support is buggy with respect to case sensitivity.
-
nilskp over 12 yearsdojo has the same thing:
dojo.subscribe("/dojo/hashchange", context, callback);
-
Paystey about 12 yearsJust to add yet another update, the
hashchange
event is now widely supported: caniuse.com/#search=hash -
Codebeat about 12 yearsBetter use: window.location.href instead of window.location.
-
Michael Martin-Smucker almost 12 years@everybody, no need to keep appending to the answer in the comments section -- that's what the "Edit" button is for. :)
-
Luc almost 12 yearsAm I the only one who thinks unsolicited jQuery answers are a pain?
-
Lèse majesté over 11 yearsWasn't able to get this to work with jQuery 1.7. The plugin doesn't seem to have been updated in 2 years.
-
undefined over 11 yearsHe's watching window.location.hash, not window.location.
-
gion_13 over 11 years@BrianMortenson: according to the docs (developer.mozilla.org/en-US/docs/JavaScript/Reference/…) you must apply
watch
to the object that owns the property that is changing and you want to observe it. -
undefined over 11 years@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.
-
mjs almost 11 years@Luc I totally agree with you! Why do all presume jQuery is always used!
-
BergP over 10 years@meandmycode can I detect change of (window.location) and handle it? (without jquery)
-
Admin about 10 yearsThis answer is now deprecated
-
VikkyB over 9 yearsBut how to know when the latest URL will be available?
-
SuperUberDuper about 9 years@Jhawins what is the new answer?
-
Admin about 9 years@SuperUberDuper the new answer is the one below this (direct link). 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. -
Mnebuerquo almost 9 yearsThe Ben Alman plugin seems to be no longer maintained. There are a number of forks though.
-
Chris almost 9 yearsusage:
window.onhashchange = function() { doYourStuff(); }
-
lele1c over 8 yearsMDN documentation of hashchange event.
-
zrajm over 7 yearsExcellent answer, but could you maybe add some info on how to read the hashlocation from that event?
-
cregox about 7 yearsthis doesn't seem to work with history manipulation. there is
window.onpopstate
but even that won't always work. -
Jason C almost 2 years@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.