Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll down the page automatically until the user scrolls up

Tags:

javascript

I got this simple script to scroll down the page

function scrollDown() {
     window.scrollBy(0,50); // horizontal and vertical scroll increments
}

scrolldelay = setTimeout('scrollDown()',100); // scrolls every 100 milliseconds

Now I wish to intercept when the user scrolls up himself to stop the setTimeout with a

clearTimeout(scrolldelay);

Any idea? Preferable with pure js

An alternative to accepted answer is here: http://jsfiddle.net/Vy8tW/

like image 379
dynamic Avatar asked Sep 06 '11 10:09

dynamic


1 Answers

var start = (function() {
    function scrollTop() {
        return window.scrollTop || document.body.scrollTop || (document.documentElement && document.documentElement.scrollTop)
    }

    var top = scrollTop();
    var interval;
    window.onscroll = function() {
        var newtop = scrollTop();
        if (newtop < top) {
            clearInterval(interval);
        }
        top = newtop;
    };
    return function() {
        interval = setInterval(function() {
            window.scrollBy(0, 50);
        }, 100);
    }
}());

start();

How it works: Each time the page is scrolled, it compares the current scrollTop to the previous one. If we detect that the page has been scrolled up, we stop the interval.

You can re-start the scroll by calling start() again.

Try it here: http://jsfiddle.net/fR9Wt/3/

like image 151
Arnaud Le Blanc Avatar answered Sep 23 '22 05:09

Arnaud Le Blanc