cmplieger cmplieger - 1 month ago 9
Ajax Question

get ajax hash url on page load

so say I set a hash when i do an ajax call:

example: http://example.com/#hash.html

if I load another page and click on the backbutton, how would i detect the hash and extract the url on load?
The rest I got already covered :).

If you need more code, please tell me. btw, i'm using jquery.

Answer

There is an event, hashchange, but it's only supported in Firefox 3.6, IE8 and I assume the latest Chromes and Safaris.

For best support, detect the hashchange event, and if not present, use a polling function with setInterval().

So you would do something like...

(function() { 

   var hash = window.location.hash;

   if ('onhashchange' in window) {
      window.onhashchange = hashChanged;
   } else {
      setInterval(function() {
         if (window.location.hash != hash) {
             hash = window.location.hash;
             hashChanged();
         }
      }, 500);
   }

   var hashChanged = function() {
     alert('Hash has changed!');
   };

})();