How to Scroll Automatically to the Bottom of the Page with JavaScript

A guide to scrolling automatically to the bottom of the page with JavaScript.

ā€¢

Sometimes, we want to scroll automatically to the bottom of the page with JavaScript.

In this article, weā€™ll look at how to scroll automatically to the bottom of the page with JavaScript.

The window.scrollTo Method

We can use theĀ window.scrollToĀ method to scroll to the bottom of the page.

For example, we can write the following HTML:

<div></div>

Then we callĀ window.scrollToĀ by writing:

const div = document.querySelector(''div'')
for (let i = 0; i < 100; i++) {
  const p = document.createElement(''p'')
  p.textContent = ''hello''
  div.appendChild(p)
}
window.scrollTo(0, document.body.scrollHeight);

We get the div withĀ querySelector.

Then we create some p elements withĀ createElementĀ and append them to the div withĀ appendChild.

Next, we callĀ window.scrollToĀ with the x and y coordinates to scroll to respectively.

document.body.scrollHeightĀ is the height of the body element and so we scroll to the bottom.

If our scroll container isnā€™t the body element, then we can also get theĀ scrollHeightĀ from whatever element we want.

For instance, we can write:

const div = document.querySelector(''div'')

for (let i = 0; i < 100; i++) {
  const p = document.createElement(''p'')
  p.textContent = ''hello''
  div.appendChild(p)
}
window.scrollTo(0, div.scrollHeight);

We use theĀ scrollHeightĀ of the div instead ofĀ document.bodyĀ .

And we get the same scrolling effect as before.

The scrollIntoView Method

We can use theĀ scrollIntoViewĀ method to scroll the screen to the element itā€™s called on.

For instance, we can write:

const div = document.querySelector(''div'')
for (let i = 0; i < 100; i++) {
  const p = document.createElement(''p'')
  p.textContent = ''hello''
  p.id = `el-${i}`
  div.appendChild(p)
}
document.querySelector(''#el-99'')
  .scrollIntoView(false);

We callĀ scrollIntoViewĀ to scroll to the element with IDĀ el-99.

The argument indicates whether we want to scroll to the top of the element or not.

Since itā€™sĀ falseĀ , we arenā€™t scrolling to the top of the element.

Also, we can change the scroll behavior by writing:

const div = document.querySelector(''div'')
for (let i = 0; i < 100; i++) {
  const p = document.createElement(''p'')
  p.textContent = ''hello''
  p.id = `el-${i}`
  div.appendChild(p)
}

document.querySelector(''#el-99'')
  .scrollIntoView({
    behavior: ''smooth''
  });

We pass in an object withĀ behaviorĀ set toĀ ''smooth''.

And so we get smooth scrolling as a result.

Conclusion

We can use JavaScript to scroll to the bottom of the page automatically.

We can scroll to the bottom of the scroll container directly or we can scroll to an element at the bottom of the page.

Continue Learning

Discover more articles on similar topics