1

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?

at.
  • 50,922
  • 104
  • 292
  • 461

4 Answers4

3

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.

Jesse Cohen
  • 4,010
  • 22
  • 25
1

I think this might answer your question:

add a hash with javascript to url without scrolling page?

Community
  • 1
  • 1
Nico
  • 2,645
  • 19
  • 25
0

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.

JoshRivers
  • 9,920
  • 8
  • 39
  • 39
0

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.

Community
  • 1
  • 1
HChen
  • 2,141
  • 13
  • 12