Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid the page scrolling/jumping when anchor is in the URL [duplicate]

Possible Duplicate:
jquery - disable anchor “jump” when loading a page

I'm displaying a div depending on the hash value in a URL but i want to avoid the page jumping to the postion of that div with that particular ID.

I only have the problem when the page is navigated direct with the hash in the URL so say for example if someone has book marked the page.

So for example I have the url domain.com/page.html#myitem-1

ID=myitem-1 will then display, which it does but the page then jumps down to the postion of that div which i don't want.

I was trying to use scrollTop(0) to force the window position back to the top but it seems as if this gets called before the anchor jump takes place to has no effect

Example code:

  $(document).ready(function() {
    $('.glossary-term').hide();
    $(window.location.hash).show();

    $(window).scrollTop(0);

});

The only way i was able to get this scrollTop to work was to place it in a setTimeOut with a duration of 1, but this seems like a bit of a hack. Any other suggestions?

Thanks

B

like image 883
Ben Avatar asked May 16 '12 21:05

Ben


1 Answers

Well, if it is your internal mechanism for using anchors just for displaying divs you can always change (or remove) the "name" attribute so the browser won't find it directly and won't try to scroll ;)

Otherwise try How to disable anchor "jump" when loading a page?

like image 68
Majki Avatar answered Oct 02 '22 13:10

Majki