bobsoap
bobsoap

Reputation: 5114

Prevent default hash behavior on page load

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:

That's exactly what I want to prevent.

Any ideas? Thanks!

Upvotes: 14

Views: 23787

Answers (4)

Sergei Smirnov
Sergei Smirnov

Reputation: 161

  1. You should just hide the element with id=hash by default
  2. Аnd then, after the page loads, you make the element visible.

You can find more info here: How to disable anchor "jump" when loading a page?

Upvotes: 0

Frank Forte
Frank Forte

Reputation: 31

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

Upvotes: 3

Mario Estrada
Mario Estrada

Reputation: 475

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

window.location = '#';

Upvotes: 1

Ian Wetherbee
Ian Wetherbee

Reputation: 6109

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

Upvotes: 48

Related Questions