farjam
farjam

Reputation: 2299

jQuery: Adding additional pixels to the scrollTop

I'm using the following code to smooth the movement when user clicks on a link that its href starts with an "#"

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash,
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
}); 

I need to add about 40px to the scrollTop value, so the stopping point doe snot cover the content. I modified the code to this, but it does not seem to be doing it (notice the +40 towards end of the code):

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash,
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top + 40
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
}); 

Upvotes: 7

Views: 23715

Answers (2)

Pexsol
Pexsol

Reputation: 561

I know a late answer but someone seeking a solution can try this.

By adding .top + (-40) will do the trick

$('html, body').stop().animate({
    'scrollTop': $target.offset().top + (-40)
}, 900, 'swing', function () {
    window.location.hash = target;
});

Upvotes: 22

Blake Plumb
Blake Plumb

Reputation: 7199

The +40 offset which you actually want to be a -40 is not working because once the animation is complete the browser is doing it's default reaction of going to the element with the id you are passing to window.location.hash

You can either remove that line or add the following css to the elements being scrolled to.

padding-top: 40px;
margin-top: -40px;

See FIDDLE

Upvotes: 3

Related Questions