views:

62

answers:

1

So I see a lot of people recommend the hidden-iFrame hack that is jQuery history plugin but all I really need is the other half of this technique:

function whenItemIsClicked()
    {
    window.location.hash = this.id;
    //some other stuff, like Ajax
    }

//and then, if page is reloaded...
$(document).ready(function(){
    var loc = window.location.hash;
    //if there happens to be a hash, navigate to corresponding content
    if(loc != '') $(loc).click();
});

Both of these work great. Now, I'd like to attach these two lines

  var loc = window.location.hash;
  if(loc != '') $(loc).click();

to an event, but it seems there isn't one that will be triggered consistently by the back button. Is there a way to add a browser history state that will save the present URL so the above technique will work?

A: 

There's an event called window.onhashchange though not everyone supports it yet, but...there's a plugin by Ben Alman to solve that issue.

The plugin that makes it work cross-browser by using window.onhashchange (the native event) if it's there, if not it polls every 50ms and triggers the event itself if the hash changes. Using the plugin, your could would look like this:

$(window).hashchange(function() {
  var loc = window.location.hash;
  if(loc != '') $(loc).click();    
});

You just need that code in one place, you can trigger it once in document.ready by just firing the event after it's bound like above doing this:

$(function(){
  $(window).hashchange();
});
Nick Craver