Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - scroll down every x seconds, then scroll to the top

I have a scrollable div that I want to scroll down 50 pixels every X seconds. That's fine and working.

I also have a seperate function that scrolls the div back to the top when it reaches the bottom. Also fine; working.

Now, I need to combine the two so the scrolldown is ignored until we have scrolled to the top again.

I have a 'working' example here, as you'll see it has some pretty nutty behavior: http://jsfiddle.net/JVftf/

window.setInterval(scrollit, 3000);

function scrollit() {
    $('#scroller').delay(2000).animate({ scrollTop: $("#scroller").scrollTop() + 50 }, 'slow');
}

$('#scroller').bind('scroll', function () {
    if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        $('#scroller').delay(2000).animate({ scrollTop: 0 }, 1000);
    }
});
like image 977
Alan Shortis Avatar asked Oct 25 '12 11:10

Alan Shortis


1 Answers

My version:

var scrollingUp = 0;

window.setInterval(scrollit, 3000);

function scrollit() {
    if(scrollingUp == 0) {
        $('#scroller').delay(2000).animate({ scrollTop: $("#scroller").scrollTop() + 50 }, 'slow');
    }
}

$('#scroller').bind('scroll', function () {
    $('#status').html(scrollingUp);

    if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
        scrollingUp = 1;      
        $('#scroller').delay(2000).animate({ scrollTop: 0 }, 1000, function() {
            scrollingUp = 0;    
        });
    }
});​

Demo: http://jsfiddle.net/EFmeK/

Btw, in your jsfiddle, it scrolls 60px instead of 50px, which I "fixed" in my example.

like image 194
sascha Avatar answered Sep 16 '22 17:09

sascha