By default, the scroll position of the page is kept after we refresh the page.
Sometimes, we want to force a page to scroll to the top when we refresh it.
In this article, we’ll look at how to force a page to scroll to the top when we refresh the page.
Listen to the beforeunload Event and use the scrollTo Method
To run code when the page refreshes, we can listen to the beforeunload
event.
Then in the beforeunload
event handler, we call the scrollTo
method to scroll to the top of the page when it refreshes.
For instance, if we have the following HTML:
<div>
</div>
Then we can write:
const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
const p = document.createElement('p')
p.textContent = i
div.appendChild(p)
}
window.onbeforeunload = () => {
window.scrollTo(0, 0);
}
to add some elements into the div with the document.createElement
method and the appenndChild
method.
Then we set the window.onbeforeunload
property to a function that calls window.scrollTo
with 0 and 0 to scroll to the top.
Now when we refresh the page, we scroll to the top of the page.
Conclusion
We can force a page to scroll to the top when we refresh the page by listening to the beforeunload
event with a listener and call scrollTo
ibn the event listener.