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.