Gradually scroll the mouse to the mouse

How can I make the viewport scroll slowly when the mouse button is pressed over an element position: fixed?

+4
source share
1 answer

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

$('html, body'), Firefox, Chrome. , animate() - . , jQuery.stop(). Firefox $('html').scrollTop(), Chrome $('body').scrollTop(), , Math.max(). clearTimeout() jQuery.stop() .

+2

Source: https://habr.com/ru/post/1661771/


All Articles