6

How can I make the viewport scroll down gradually while the mouse button is pressed down over a position: fixed element?

Scott Hunter
  • 385
  • 5
  • 24
  • When scrolling, won't the mouse cursor come off the element they're holding down? If you meant "on click" rather than holding, then check this out: [Javascript smooth scroll WITHOUT the use of jQuery](https://stackoverflow.com/questions/10063380/javascript-smooth-scroll-without-the-use-of-jquery) or [this](https://www.sitepoint.com/smooth-scrolling-vanilla-javascript/) – Jason Cemra Nov 24 '16 at 00:23
  • Thanks but it would be a fixed element they hold down – Scott Hunter Nov 24 '16 at 00:27

1 Answers1

6

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.

Daerik
  • 4,167
  • 2
  • 20
  • 33
  • Works great, thanks! is there a way to make it a little smoother ? – Scott Hunter Nov 24 '16 at 01:21
  • @ScottHunter There are supplemental scripts that add to easing in the default jQuery library. There are really only 3 settings: linear, swing, and default. You can find scripts that create smoother transitions. – Daerik Nov 24 '16 at 01:30