Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth Scroll Using window.scrollBy

I'm trying to smoothly scroll a page using setInterval() and window.scrollBy()

I would use jQuery's animate function, but the animation needs to be continuous and loop infinitely (the page contents will be infinite).

The idea is fairly simple:

var x = 1;
var y = 1;

setInterval(function() {
    window.scrollBy(0, x);
}, y);

How can I increase the scroll speed without making the animation appear jumpy?

I'm experience two problems:

  1. setInterval() can't take a Y value less than 1 (or probably closer to 30, depending on browser limits)
  2. Increasing the value of X causes the animation to be jumpy (due to pixels being skipped altogether)

Here's a fiddle to experiment with:

http://jsfiddle.net/eoojrqh6/2/

Thanks!

like image 895
coryetzkorn Avatar asked Mar 11 '15 02:03

coryetzkorn


3 Answers

You can also scroll other elements:

document.querySelector('.el-class').scrollBy({
  top: 100,
  behavior: 'smooth',
});
like image 82
AliN11 Avatar answered Oct 27 '22 09:10

AliN11


Use behavior option instead of setInterval its more simple and it's the right way to do this,

var x = 1;
var y = 1;

window.scrollBy({
    top: x,
    left: y,
    behavior : "smooth"
})
like image 41
Rohit Nishad Avatar answered Oct 27 '22 09:10

Rohit Nishad


Rather than window.scrollBy you can use window.scroll.

http://jsfiddle.net/peterdotjs/f7yzLzyx/1/

var x = 1; //y-axis pixel displacement
var y = 1; //delay in milliseconds

setInterval(function() {
    window.scroll(0, x);
    x = x + 5; //if you want to increase speed simply increase increment interval
}, y);

As you currently have y value set very low, you can adjust the values of y and the incremental value of x to find the desired scroll speed.

like image 10
peterdotjs Avatar answered Oct 27 '22 11:10

peterdotjs