Smooth Scrolling anchor with offset (jquery)
Asked Answered
C

2

7

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;
        }
    }
});
Cystectomy answered 17/6, 2016 at 12:49 Comment(0)
B
13

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;
        }
    }
});
Beyond answered 17/6, 2016 at 13:43 Comment(1)
This solution works nicely, but it does not change the URL to #anchor. So the user cannot link directly to the url with anchor.Vinaigrette
E
4

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);
});
Encase answered 16/7, 2019 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.