How can I make the viewport scroll down gradually while the mouse button is pressed down over a position: fixed
element?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With