Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth Scrolling anchor with offset (jquery)

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;
        }
    }
});
like image 934
PahPow Avatar asked Jun 17 '16 12:06

PahPow


2 Answers

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;
        }
    }
});
like image 160
Vinicius de Castro Avatar answered Sep 29 '22 11:09

Vinicius de Castro


A simpler example with no hash is:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top + -200
    }, 1000);
});
like image 32
BlueDogRanch Avatar answered Sep 29 '22 11:09

BlueDogRanch