I am building a Html 5 website using push state and I wondering whether its possible in javascript or JQuery to detect whether the browser’s back button has been pushed. I would like to include it in an if statement like so:
if (back_btn clicked){
//do stuff
}
if (forward_btn clicked){
}
Advertisement
Answer
You’re looking for the popstate event.
An example:
window.onpopstate = function(event) {
alert("location: " + document.location);
}
Or with the ever-popular jQuery:
$(window).on('popstate',function(event) {
alert("location: " + document.location);
});
This fires whenever history is accessed, such as back/forward. A quick note, in Chrome this also fires on the page load, so a quick way around is to check if the event is null.
if(event.originalEvent.state!=null){
// do something
}
Another good resource is the History.js jQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.