Search code examples
jqueryscrollsmoothing

jquery smooth variable scroll to element id


I am using the following script to scroll the user to an element. It works nicely, but I was wondering if there was a way I could make the scroll a bit smoother.

At the moment it scrolls at a set speed, but I was hoping it could accelerate to speed and then decelerate to a stop to give a much smoother experience.

Could anyone advise me on how to do this?

Many thanks

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 1000);
});

Solution

  • Just include jQuery UI / jQuery easing. This will allow you to use the different easing options provided, i.e:

    $(function(){
    $('#button').click(function() {
        $('html, body').animate({
            scrollTop: $("#elementtoScrollToID").offset().top
        }, 1000, 'easeOutCubic');
    });
    });