2690

Smooth-scrolling to another page’s anchor link while automatically adding a fixed navigation height The jQuery code that is also minus in

Smooth-scrolling to another page’s anchor link while automatically adding a fixed navigation height The jQuery code that is also minus in

2019.6.7

Personally, I think the homepage is most efficient with a simple behavior, but you can fix the navigation and I want to anchor the headline to a minus position. Or, on the contrary, there are a lot of requests to make it more complicated.

Well, since it’s my job, I make this kind of behavior, but this time it took me a long time to make that behavior, so I had to make I’ll paste the working code.

code

 var headerHeight = $('.header').outerHeight(); //Get the height of the fixed header.
var urlHash = location.hash; //Get the URL hash
var animeSpeed = 500; //The animation speed of the scroll
if(urlHash) {
    $('body,html').stop().scrollTop(0);
    setTimeout(function(){
        var target = $(urlHash);
        var position = target.offset().top - headerHeight;
        $('body,html').stop().animate({scrollTop: {scrollTop: position}, animeSpeed);
    }, 100);
}
$('a[href^="#"]').on({
    'click': function(){
        var href= $(this).attr("href");
        var target = $(href);
        var position = target.offset().top - headerHeight;
        $('body,html').stop().animate({scrollTop: position}, animeSpeed);
    }
});

Conclusion

Smooth scrolling is easy when jumping to another anchor on a page that you’re already on, but it’s a different page And it gets so complicated.