简体   繁体   中英

jQuery repeat Autoscroll Top to Bottom and Bottom to Top with x time

I'm continuing this question for Autoscroll to bottom of page then top and repeat.

Here is a JS Fiddle .

As you can see on that fiddle, when page loaded it directly scroll to bottom. I want when page loaded, wait about 10 seconds and then scroll it to bottom. Same if the scroll on bottom page, wait about 10 seconds and then scroll it to top.

Code:

$("html, body").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('html, body').animate({scrollTop:0}, 4000); 
},4000);
setInterval(function(){
 // 4000 - it will take 4 secound in total from the top of the page to the bottom
$("html, body").animate({ scrollTop: $(document).height() }, 4000);
setTimeout(function() {
$('html, body').animate({scrollTop:0}, 4000); 
},4000);

},8000);

You can do it with just one interval, taking into account the time the scroll animation takes...

$("html, body").animate({ scrollTop: $(document).height() }, 4000);

setInterval(function(){
    $("html, body").animate({ scrollTop: ($(window).scrollTop()==0 ? $(document).height() : 0) }, 4000);
},14000);

You don't mention what happens if the user change manually the scroll to an intermediate position. With this solution, after the current 10 seconds interval the scroll will go back to top and start again.

I hope it helps...

It is a bit weird. You may want this

$(function() {
    down();
    function up() {
        setTimeout(function() {
            scroll(0, down);
        }, 10000);
    }
    function down() {
        setTimeout(function() {
            scroll($(document).height(), up);
        }, 10000)
    }    
    function scroll(pos, callback) {
        $('html, body').animate({
                scrollTop: pos
         }, 4000, callback);
    }
})

http://jsfiddle.net/tamvo/wzr50zm8/

Please replace your js code with the one mentioned below and it should serve your purpose

function scrollToTop(){
    setTimeout(function(){
    $('html, body').animate({scrollTop:0}, {
        duration: 4000,
        complete: function(){
          scrollToBottom();
        }
    }); 
  },10000);
}

function scrollToBottom(){
    setTimeout(function(){
    $('html, body').animate({scrollTop:$(document).height()}, {
        duration: 4000,
        complete: function(){
          scrollToTop();
        }
    }); 
  },10000);
}

scrollToBottom();

Fiddle link: http://jsfiddle.net/jdb8rw0L/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM