Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate URL anchor but don't scroll to it?

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 ??

like image 706
DisgruntledGoat Avatar asked Sep 05 '09 23:09

DisgruntledGoat


2 Answers

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).

like image 122
Tom Ritter Avatar answered Sep 24 '22 00:09

Tom Ritter


A quick hack:

var thehash = e.target.hash;
$(thehash).prop('id',thehash.substr(1)+'-noscroll');
window.location.hash = e.target.hash;
$(thehash+'-noscroll').prop('id',thehash.substr(1));     

This changes the id of the html element before and after changing the hash of the url. Works for me, but might as well break something. This prevents the browser from scrolling on a hash change, since there is not html element with that id in between.

like image 38
devsnd Avatar answered Sep 27 '22 00:09

devsnd