Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 591
Joey Avatar asked Jul 07 '12 23:07

Joey


People also ask

How can I see what was clicked on JavaScript?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.


2 Answers

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.

like image 169
jgivoni Avatar answered Oct 06 '22 23:10

jgivoni


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

like image 37
Alex Avatar answered Oct 07 '22 00:10

Alex