Search code examples
jqueryscrollwindowanchor

Link to Anchor under Fixed Header from Another Page


I'm trying to link to an anchor on one page (Page 1) from another one (Page 2). Both pages have a fixed header. As such, I'm using the follow script on both pages:

$(document).ready(function(){
    $('.testlink').bind('click', function(e) {
        e.preventDefault();
        var sHref = this.href.split("#"); 
        var topDistance = $("#"+sHref[1]).position().top;
        var tds = topDistance - 146 ;
        $("html, body").animate({ scrollTop: tds }, 'slow');            
        return false;           
    });
});

Example link:

<a href="../plan/medical.html#howdeductworks">How the deductible works</a>

Example anchor link:

<a id="howdeductworks"></a>

This links to the anchor, then offsets it, so that the anchor isn't under the header.

When I link to an anchor from Page 1 to an anchor on Page 1, everything works fine. When I link to one on another page, the script doesn't work and anchor is underneath the header.

I tried recoding it like this:

$(document).ready(function(){
    $('.testlink').bind('click', function(e) {
        e.preventDefault(); 
        $(location).attr( 'href', $(this).attr('href') );
        var sHref = this.href.split("#"); 
        var topDistance = $("#"+sHref[1]).position().top;
        var tds = topDistance - 146 ;
        $("html, body").animate({ scrollTop: tds }, 'slow');
        return false;           
    });
});

...but that didn't work. Perhaps I wrote what I wanted to do incorrectly. If so, I would appreciate some help.

BTW, as mentioned above, when click to an anchor from the link on the same page, the page doesn't refresh - it just goes to the anchor. I'd like for that to stay, if possible (meaning no refresh). If the link is coming from another page, yes, refresh/load the page.


Solution

  • try this

        function scrollToAnchor(anchor) {
                $("html, body").animate({ scrollTop: $(anchor).position().top - 146 }, 'slow');
        }
    
        $(document).ready(function() {
            $('.testlink').bind('click', function(e) {
                e.preventDefault(); 
                var sHref = this.href.split("#"); 
                scrollToAnchor("#"+sHref[1]);
                return false;           
            });
    
            //now scroll to the anchor when loading page - this was missing
            scrollToAnchor(document.location.hash);
        });