Search code examples
javascriptloopsscrollinfinite-loopinfinite-scroll

Javascript page scrolls automatically up and down


I'm struggling with a challenge that is just a bit out of my skill range. I'm trying to make a page scroll (very slowly) up and down on an infinite loop. I got the code to loop once, but my challenge is to make it loop over and over again. I would love advice.

do {
$(document).ready(function(){
     $('body,html').animate({scrollTop: 2650}, 57820);
  
});

$(document).ready(function(){
     $('body,html').animate({scrollTop: 0}, 35000);
  
});
}
while (true === true);


Solution

  • Javascript code is mainly asynchronous. What this means for you is that the browser is running the "go to top" and "go to bottom" code rapidly. And thus crashes your browser. What you want, is to wait till the scroll to bottom is completed, then scroll to top. Here is an example that does what you want.

    // Getting a reference to html. The way you did it in the loop
    // is slow because it has to get access to it every time.
    const main = $('html');
    
    // The scrollTop function
    // scrolls to the top
    function scrollTop() {
        console.log('scrolling to top')
        main.animate({scrollTop: 0},1000,"linear",scrollBottom /* this is a callback it means when we are done scrolling to the top, scroll to the bottom */)
    }
    
    function scrollBottom() {
        console.log('scrolling to bottom')
        main.animate({scrollTop: document.body.offsetHeight},1000,"linear",scrollTop /* this is a callback it means when we are done scrolling to the bottom, scroll to the top */)
    }
    
    // this kicks it off
    // again only running $(document).ready once to increase performance.
    // Once scrollTop completes, it calls scrollBottom, which in turn calls scrollTop and so on
    $(document).ready(scrollTop);