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.