Smooth Scrolling anchor with offset (jquery)

PahPow picture PahPow · Jun 17, 2016 · Viewed 8.1k times · Source

Im using the following code to add smooth scrolling for anchors on my site. Because i have a sticky header id like to offset this by say 200px

$('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});

Answer

Vinicius de Castro picture Vinicius de Castro · Jun 17, 2016

Try add or remove a value in the scrollTop animation

$('a[href*="#"]:not([href="#"])').click(function() {
    var offset = -200; // <-- change the value here
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top + offset
            }, 1000);
            return false;
        }
    }
});