Search code examples
javascriptjqueryhtmlscrollsmooth-scrolling

Why isn't my smooth scrolling smooth?


I'm using the following code to smooth scroll down a fairly large document:

$("html, body").animate({
scrollTop: $('#article').offset().top + $('#article').outerHeight(true)
}, 500);

I believe this is because the its spanning too great of a distance. On smaller articles (i.e. instances where the div #article takes up less height) it scrolls smoothly. Is there a dynamic way to adjust the scrolling time to avoid choppy displays, or is there some other solution?


Solution

  • You can try a simple equation between article height and duration .. for example you can set the duration like this .. or change it up to your need

    //this is just for example
    var duration = ($('#article').outerHeight(true) / 100) * 500 ;
    //or
    //var duration = (($('#article').offset().top + $('#article').outerHeight(true)) / 100) * 500 ;
    
    $("html, body").animate({
    scrollTop: $('#article').offset().top + $('#article').outerHeight(true)
    }, duration);
    

    Working Demo .. change #article height in css to see the effect