let user scrolling stop jquery animation of scrolltop?

Diode’s solution didn’t work for me – scroll() didn’t differentiate between the animation and the user, meaning the animation stopped immediately. From a different post, the following works for me (modified for this purpose):

// Assign the HTML, Body as a variable...
var $viewport = $('html, body');

// Some event to trigger the scroll animation (with a nice ease - requires easing plugin )...
$('#element').click(function() {
    $viewport.animate({ 
        scrollTop: scrollTarget // set scrollTarget to your desired position
    }, 1700, "easeOutQuint");
});

// Stop the animation if the user scrolls. Defaults on .stop() should be fine
$viewport.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
         $viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); // This identifies the scroll as a user action, stops the animation, then unbinds the event straight after (optional)
    }
});                 

Leave a Comment