D.C.
D.C.

Reputation: 15588

Animating window scrolling

Hi I am using the following method to programmatically scroll a web document:

window.scrollBy(0, delta)

The current implementation of scrollBy just jumps the document to the new position. Is there a way of animating this? I am using webkit specifically, and jQuery (or any other javascript framework) is not an option.

Thanks for any help in advance.

Upvotes: 4

Views: 10378

Answers (2)

mmm
mmm

Reputation: 2297

Every time this function is called, it will jump the number of pixels in window.scrollBy (0,5), regardless of where the pageYOffset is. For instance, if pageYOffset is 300px, it will jump to 305px.

but this problem can be solved by moving the if and adding an else
like so:

var timerID = setInterval(function() {
    if( window.pageYOffset <= 500 )
        window.scrollBy(0, 5);

    else
        clearInterval(timerID);
}, 1);

Upvotes: 0

jAndy
jAndy

Reputation: 236032

You can just animate it by invoking an interval:

setInterval(function() {
    window.scrollBy(0, 5);
}, 13);

This of course would do it over and over, so you need to put in a conditional check, when to cancel the interval. Could look like:

var timerID = setInterval(function() {
    window.scrollBy(0, 5);

    if( window.pageYOffset >= 500 )
        clearInterval(timerID);
}, 13);

Upvotes: 13

Related Questions