Using Back and Down Browser Buttons for Web Applications

advertisements

How do I use the back and forward browser buttons to navigate my javascript/jQuery web application? I know I can do window.location.href = 'this_url#placeholder' and then perform the appropriate action. But when I do that, the browser scrolls to the element with that placeholder id (or to the top if there wasn't one). How do I get the browser to not scroll anywhere? I've seen this on other sites like facebook, what's the appropriate mechanism for this?


if you use location.hash instead of location.href the behaviour you specify shouldn't happen.

The HTML5 standard specifies new history features e.g. history.pushState() which offer a nice replacement for this, but not all browsers support it yet.

If you don't want to roll your own framework, there are a number of javascript plugins which offer this functionality all packaged up nicely for easy use across browsers with slightly differing implementations. For example jquery history will use the newer history options on browsers that support it and fall back to hash urls in browsers that don't.