Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent default hash behavior on page load

Tags:

jquery

I have a page with a tabbed interface. Each tab has a unique id. I've enabled links pointing to that page with the appended id after the hash, and I'm now trying to circumvent the default browser behavior that opens a URL with hash at the location of the element on the page.

So:

  • pageA links to pageB like this: <a href="pageB.php#Tab4">Go</a>
  • pageB opens, and my jQuery activates the correct tab, but the browser has scrolled down to where <div id="Tab4"> is located on the page.

That's exactly what I want to prevent.

Any ideas? Thanks!

like image 896
bobsoap Avatar asked Aug 17 '10 14:08

bobsoap


3 Answers

There isn't a way to prevent the default hash behavior, but you can alter your hash scheme so the #tag doesn't correspond to any ID on your page. On page load, take the hash value and append a constant (ex: _hash), then scroll to that using jQuery.

Example: http://mysite/page.php#tab4

page.php has <div id="tab4_hash"></div>

On page load, get the div by doing tab4 + _hash

like image 164
Ian Wetherbee Avatar answered Oct 18 '22 04:10

Ian Wetherbee


I would use this:

window.scrollTo(0,0);

This way you don't need to change element id's or anything else.

I came across the problem where I wanted to scroll down to the tab, but for some reason it scrolled past it to the bottom of the page (no, there was not a duplicate id). I think it is because the browser would scroll to the id before the content finished loading, and the extra content pushed the element above the new scroll position). I fixed it with this:

if(document.location.hash)
{
    window.location = document.location.hash;
}

the "if" statement here is mandatory or you might get an infinite loop

like image 30
Frank Forte Avatar answered Oct 18 '22 03:10

Frank Forte


After you're done loading the right tab, run this:

window.location = '#';
like image 42
Mario Estrada Avatar answered Oct 18 '22 03:10

Mario Estrada