Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Adding additional pixels to the scrollTop

Tags:

jquery

css

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;
        });
    });
}); 
like image 747
farjam Avatar asked May 13 '13 18:05

farjam


2 Answers

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;
});
like image 111
Pexsol Avatar answered Nov 10 '22 04:11

Pexsol


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

like image 35
Blake Plumb Avatar answered Nov 10 '22 02:11

Blake Plumb