views:

911

answers:

5

I have a page with two tabs that I want to be able to switch with Javascript, but also set the anchor (e.g. page.html#tab1) in the URL for bookmarking/linking.

By default the tab contents are in two divs, one below the other, and the anchor tag will scroll to the correct one, with JS disabled.

With JS enabled, CSS classes are applied to make them act as tabs. Each tab links to each anchor, but when you click to switch tabs, the page scrolls to the tab. If I return false from the onclick function then the URL doesn't change to include the anchor.

How do I make the browser URL change to page.html#tab1 but not scroll to #tab1 ??

A: 
window.location.hash = 'tab1';

might work.

Jani Hartikainen
No it won't, that will scroll to the anchor (except in Safari in certain cases, thanks to its broken location.hash support).
andynormancx
A: 

Not perfect, but should works: You could after load all script run:

scroll(0,0)

it scroll page return to top ;)

Rin
This breaks in the (very likely) case that the user has already scrolled down the page a little before clicking the link.
DisgruntledGoat
A: 

Could you have some Javascript that changed the anchor names, set window.location.hash, and then changed the anchor names back?

(I've confirmed that andynormancx is right, and setting window.location.hash scrolls the view, but I'm too lazy to test if creating an anchor in the DOM to window.location.hash also scrolls.)

Alec
+2  A: 

I've played with this for a while, because I initially didn't believe you (I use the jQuery history plugin to get similar behavior).

And I'm stumped. I don't think you can. What you could do, as a workaround, is use javascript to set the hash to something DIFFERENT from what is actually on the page. And then use javascript upon load to read the hash and populate the correct content. I do this on my site. So in that scenario, users without javascript would be scrolled, users with javascript would keep the history chain, and it only gets wacky when people without send links to people with (or vice-versa).

Tom Ritter
This works, and I just discovered that's what validator.w3.org does. In the end I decided to scrap making the anchor jump to the right place in non-JS browsers since the two divs are not very tall, and as you say links from JS-enabled users for non-JS users stops it working.
DisgruntledGoat
A: 
var Namespace = {
  var timer, scroll;
}

// Onclick
Namespace.scroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
Namespace.timer = setInterval(function() { scrollTo(0, Namespace.scroll) }, 100);
location.hash = this.href;
clearInterval(Namespace.timer);
Josh Stodola