Scott Hunter Scott Hunter - 5 months ago 36
Javascript Question

Gradually scroll on mousedown until mouseup

How can I make the viewport scroll down gradually while the mouse button is pressed down over a

position: fixed


Here you can accomplish this with jQuery.animate() in combination with setTimeout() and clearTimeout():

$('.button').on('mousedown', function() {
    console.log('Start Animate');
    (function smoothSrcroll() {
        console.log(Math.max($('html').scrollTop(), $('body').scrollTop()));
        $('html, body').stop().animate({
            scrollTop: Math.max($('html').scrollTop(), $('body').scrollTop()) + 100
        }, 1000, 'linear', function() {
            window.timeout = setTimeout(smoothSrcroll(), 0);
}).on('mouseup', function() {
    console.log('Stop Animate');
    $('html, body').stop();

CodePen Demo

I'm targeting $('html, body') so that it will work in both Firefox and Chrome. This gets a little tricky because the animate() actually runs twice because of the two selectors. To solve this I've used jQuery.stop(). Since Firefox can use the $('html').scrollTop() and Chrome uses the $('body').scrollTop(), I calculated the increment using Math.max(). The function is self-executing upon completion and uses clearTimeout() and jQuery.stop() when the mouse is released.