Search code examples
jquerytabshref

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


I think this may not be possible, will try and explain as best as I can. I have a page containing tabs (jquery powered), controlled by the following:

I'm using this code, as provided by another user from a previous question.

<script type="text/javascript">
    $(function() {

     $('html, body').animate({scrollTop:0}); // this is my "fix"

        var tabContent = $(".tab_content");
        var tabs = $("#menu li");
        var hash = window.location.hash;
     tabContent.not(hash).hide();
        if(hash=="") {
      $('#tab1').fadeIn();
     }
        tabs.find('[href=' + hash + ']').parent().addClass('active');

        tabs.click(function() {
            $(this).addClass('active').siblings().removeClass('active');
            tabContent.hide();
            var activeTab = $(this).find("a").attr("href");

            $(activeTab).fadeIn();
           return false;
        });

    });
</script>

this code works great when I visit the "tabs" page directly.

however, I need to link to invidual tabs from other pages - so to do this, the code gets the window.location.hash then shows the appropiate tab.

the page doesn't "jump" to the anchor because of "return false".

this event is only triggered on a click event however. hence, if i visit my "tabs" from any other page, the "jump" effect is triggered. To combat this I automatically scroll to teh top of the page, but I would rather this didn't happen.

is there any way to simulate "return false" when the page loads, preventing the anchor "jump" from occuring.

hope this is clear enough.

thanks


Solution

  • Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:

    if (location.hash) {
      setTimeout(function() {
    
        window.scrollTo(0, 0);
      }, 1);
    }
    

    Edit: tested and works in Firefox, IE & Chrome on Windows.
    Edit 2: move setTimeout() inside if block, props @vsync.