at.
at.

Reputation: 52540

Utilizing back and forward browser buttons for web apps

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?

Upvotes: 1

Views: 324

Answers (4)

Jesse Cohen
Jesse Cohen

Reputation: 4040

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.

Upvotes: 3

HChen
HChen

Reputation: 2141

You can add return false after that or event.preventDefault.

$("a#some_id").click(function(){
  // do something cool
  return false; // don't scroll to #some_id
});

See this thread for relevant discussion.

Upvotes: 0

JoshRivers
JoshRivers

Reputation: 10290

Just use placeholders that are not actually defined in the page. If you have

<a name="contents">

Then use

<a href="#contentsarea">Contents</a>

To activate the contents section. The browser only scrolls if the hashtag has an anchor in the page.

Upvotes: 0

Nico
Nico

Reputation: 2663

I think this might answer your question:

add a hash with javascript to url without scrolling page?

Upvotes: 1

Related Questions