Steven Noble
Steven Noble

Reputation: 10415

Is there a way to catch the back button event in javascript?

Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.

Upvotes: 66

Views: 117214

Answers (5)

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

Use the hashchange event:

window.addEventListener("hashchange", function(e) {
  // ...
})

If you need to support older browsers, check out the hashChange Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.

Upvotes: 33

JulianW
JulianW

Reputation: 1017

Check out history.js. There is a html 5 statechange event and you can listen to it.

Upvotes: 3

Tom Penzer
Tom Penzer

Reputation: 113

I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.

What I ended up doing was creating an object as such:

var pageload = {
    ignorehashchange: false,
    loadUrl: function(){
        if (pageload.ignorehashchange == false){
            //code to parse window.location.hash and load content
        };
    }
};

Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:

window.addEventListener("hashchange", pageload.loadUrl, false);

Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:

pageload.ignorehashchange = true;

and then the following line after each hash modification line:

setTimeout(function(){pageload.ignorehashchange = false;}, 100);

So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.

Upvotes: 8

powtac
powtac

Reputation: 41040

Did you took a look at this? http://developer.yahoo.com/yui/history/

Upvotes: 0

pix0r
pix0r

Reputation: 31280

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

Upvotes: 1

Related Questions