views:

562

answers:

5

I have a Ajax heavy application that may have a URL such as

http://mysite.com/myApp/#page=1

When a user manipulates the site, the address bar can change to something like

http://mysite.com/myApp/#page=5

without reloading the page.

My problem is the following sequence:

  1. A user bookmarks the first URL.
  2. The user manipulates the application such that the second URL is the current state.
  3. The user clicks on the bookmark created in step 1.
  4. The URL in the address bar changes from http://mysite.com/myApp/#page=5 to http://mysite.com/myApp/#page=1, but I don't know of a way to detect the change happened.

If I detect a change some JavaScript would act on it. Any ideas?

+1  A: 

Do you mean something like this : http://innonesen.se/widgets/tabs/ ? I played with this code fragmet few days ago ..

azazul
+3  A: 

check the current address periodically using setTimeout/interval:

 var oldLocation = location.href;
 setInterval(function() {
      if(location.href != oldLocation) {
           do your action
           oldLocation = location.href
      }
  }, 1000); // check every second
stereofrog
This answer is correct. You should also consider using something like the YUI History manager componentry, which does it for you, in a cross-browser way.
Jonathan Feinberg
If I type in a new address and press Enter there is no way the current page will be able to stop that.
ZippyV
Yeah, I was hoping there was a hidden event or something. Using an interval just doesn't seem "right" to me somehow. Thanks.
JoshNaro
+1  A: 

You should extend the location object to expose an event that you can bind to.

ie:

window.location.prototype.changed = function(e){};

(function() //create a scope so 'location' is not global
{
    var location = window.location.href;
    setInterval(function()
    {
     if(location != window.location.href)
     {
      location = window.location.href;
      window.location.changed(location);
     }
    }, 1000);
})();

window.location.changed = function(e)
{
    console.log(e);//outputs http://newhref.com
    //this is fired when the window changes location
}
Skawful
+1  A: 

SWFaddress is an excellent library for these types of things.

moritzstefaner