8

Im using History.js (click) with jQuery in my code.

When loading new content via ajax i use:

History.pushState({my:stateobject},"newtitle","supernewurl");

This seems to work since the URL is updated in the browser.

However, I don't get it where I can hook up my code whenever a back or forward button is pressed. Which method/event is used for this?

John
  • 1
  • 13
  • 98
  • 177
Joey
  • 329
  • 2
  • 6
  • 14
  • Solution here: http://stackoverflow.com/questions/10632483/pushstate-and-popstate-manipulating-browsers-history – Bram Vanroy Jul 07 '12 at 23:21

3 Answers3

9

You need to bind an event handler to the statechange event, like this:

$(window).bind('statechange',function(){
// Do something, inspect History.getState() to decide what
})

There is a complete javascript snippet that comes with History.js, which can be used to 'ajaxify' a site completely: https://github.com/browserstate/ajaxify

Take a look there for more inspiration.

balupton
  • 47,113
  • 32
  • 131
  • 182
jgivoni
  • 1,605
  • 1
  • 15
  • 24
  • 3
    why was this downvoted? this is the correct thing to do...although I would probably do something like: `History.Adapter.bind(window,'popstate',function(){ $modalContext.modal('close'); });` – chug2k Jan 31 '13 at 08:12
4

You wouldn't capture the back click event, as there is none.

What you want to do is make sure the history object is in the right state by using window.history.pushState, window.history.popState, window.history.replaceState methods.

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Alex
  • 34,899
  • 5
  • 77
  • 90
2

I was able to use the "onPopState" event to trigger my custom AJAX code.

window.onpopstate = function(event) {
  $(fellowModal).foundation('reveal', 'close');
};

I tried several other things and that is what worked for me.

Chris Roane
  • 129
  • 1
  • 3