4

How can you detect a window.location.hash onchange, for example I could do this:

if(window.location.hash.hasChanged())
{
   // ajax stuff
}
else
{
   // nothing, no hash has been changed (without any window reload)
}

If I change the hash, e.g. edits and change the hash by pressing enter after editing nothing happens, only on a window reload will detect a change in the hash.

MacMac
  • 34,294
  • 55
  • 151
  • 222

2 Answers2

17

Most recent browsers (FF3.6+, IE8, Chrome) support the "hashchange" event on the window object - see MDC: window.onhashchange for usage examples. Simple asynchronous listening might look like:

window.onhashchange = function() {
   // do something awesome here
};

If you want an implementation that supports older browsers, things get complicated quite quickly, and I recommend using someone else's library or plugin - see answers to this question for several suggestions.

Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
2

Ben Alman's hashchange jQuery plugin provides the ability to monitor the hash for changes.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662