How can I detect the back/forwards buttons being clicked when using History.js?
Asked Answered
A

3

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?

Anthropophagi answered 7/7, 2012 at 23:16 Comment(1)
Solution here: #10632983Caesura
A
8

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.

Arezzo answered 13/7, 2012 at 19:53 Comment(1)
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'); });Alodi
R
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

Remarque answered 7/7, 2012 at 23:24 Comment(0)
E
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.

Elasticity answered 8/10, 2013 at 16:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.