Dan
Dan

Reputation: 153

JavaScript: Keep scrolling down page

I'm pretty new to JavaScript. I want to scroll to the very bottom of a website that continually loads more text when you scroll down (like on a Facebook page).

I know the code window.scrollTo(0,document.body.scrollHeight) will scroll to the bottom, causing more of the page to load, but not yet all of it. I was wondering how to execute this until the actual bottom of the page has loaded, or ~100 times.

I tried a for loop, but it didn't scroll more than once. Then I tried a for loop with setTimeout set to 2000 ms (or 2 sec) which also did not work for some reason.

I'm also worried that the page will try to run my code all at once before loading more of the content.

Thanks in advance!

Upvotes: 1

Views: 3563

Answers (2)

theboyofdream
theboyofdream

Reputation: 519

You can achieve same using scrollBy function :

function scrolldown() {
  setTimeout(
    function(){
      window.scrollBy(0,50);
      scrolldown();
    }, 1000)
}
scrolldown()

while window.scrollBy(x,y) used to scroll x & y from Top Left of the page.

Upvotes: 1

Dan
Dan

Reputation: 153

I figured it out, inspired by some other code I found online. I did:

function scrolldown() {
  setTimeout(
    function()
    {
      window.scrollTo(0,document.body.scrollHeight);
      scrolldown();
    }, 2000
  )
}

scrolldown()

Still unsure why the delayed for loop did not work though. The unsuccessful for loop attempt was:

for(var i=0; i<100; i++){
  setTimeout(
    function(){window.scrollTo(0,document.body.scrollHeight);}, 2000
  )
}

Upvotes: 2

Related Questions