Sometimes, we need to scroll to the top of a web page programmatically.
In this article, we’ll look at how to scroll to the top of the page with JavaScript.
Scroll to the Top of the Page with JavaScript
We can scroll to the top of the page with JavaScript with the window.scrollTo
method.
For instance, if we have the following HTML code:
<div>
</div>
<button>
scroll to top
</button>
Then we can create a page of content with JavaScript and make the button scroll to the top of the page by writing:
const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = 'hello'
div.appendChild(p)
}
button.addEventListener('click', () => {
window.scrollTo(0, 0);
})
We get the div with querySelector
.
Then we have a for loop which creates a p
element with document.createElement
.
And we set textContent
to it.
And then we call appendChild
to append the p
element to the div.
To make the button scroll the page to the top when we click it, we call addEventListener
on the button.
In the callback, we call window.scrollTo
with the x and y coordinates to scroll to respectively.
Smooth Scrolling Animation
We can add smooth scrolling animation when we’re scrolling.
To do this, we pass in an object to scrollTo
instead.
For instance, we can write:
const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.textContent = 'hello'
div.appendChild(p)
}
button.addEventListener('click', () => {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
});
})
We pass in an object with the top
and left
properties to set the x and y coordinates to scroll to respectively.
Also, we set the behavior
property to 'smooth'
to make the scrolling animation smooth.
This is better making the page jump straight to the top without the behavior
options as we have in the first example.
Conclusion
We can use the window.scrollTo
method to make a page scroll to the top with JavaScript.
We can set the location to scroll to and whether animation is shown or not during scrolling.