Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 element?

like image 218
Scott Hunter Avatar asked Nov 24 '16 00:11

Scott Hunter


1 Answers

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();
    clearTimeout(window.timeout);
});

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.

like image 120
Daerik Avatar answered Oct 04 '22 03:10

Daerik