views:

664

answers:

2

Does anyone know how to get a page load event to fire if the page anchor in the URL changes, i.e., going from

http://mywebsite.com/#test1  
to 
http://mywebsite.com/#test2

when using the Back button?

I tried the code at the bottom (the history.navigationMode line along with the ready() function insures that the onload event fires even when the browsers Back button is used), but it doesn't work if only the page anchor portion of the URL changes and the Back button is used. I know this code works if the URL changes it's query string (or the URL points to a new file/folder) because I use this all the time but it looks like jQuery's ready() function doesn't fire when the Back button is used if only the page anchor location in the URL changes.

I'm trying to come up with a solution for making the browser's Back button preserve JavaScript/AJAX manipulations of the page and I'm basing my attempt on this person's idea: http://www.ajaxonomy.com/2008/web-design/a-better-ajax-back-button-part2 but without relying on using a repeating timer to check if the URL page anchor has changed - I would rather check this when the page onload event fires.

Any ideas/suggestions?

<script language="javascript" type="text/javascript" src="/jquery.js"></script>
<script language="javascript" type="text/javascript">
history.navigationMode = 'compatible';
$(document).ready( function() {
   if(document.location.hash){
      var hashQueryString = document.location.hash;
      hashQueryString = hashQueryString.replace("#","");
      alert(hashQueryString);
   }
});
+2  A: 

In the near future we will have the onhashchange event, it's being introduced on new browsers, IE8 already supports it.

But for now, I recommend you to give a look to the following workarounds:

CMS
Thanks! I'll take a look at that!
Bill
You're welcome, good luck!
CMS
+1  A: 

There's a jQuery plugin you can use and a great Railscasts episode to show you how to use it (the screencast is not Rails specific).

Andy Gaskell