Sometimes, we want to force a page scroll position to the top at page refresh with JavaScript.
In this article, we’ll look at how to force a page scroll position to the top at page refresh with JavaScript.
Force a Page Scroll Position to the Top at Page Refresh with JavaScript
To force a page scroll position to the top at page refresh with JavaScript, we can use the window.scrollTo
method to scroll the page to the position we want in the beforeunload
event handler.
For instance, we can write:
window.onbeforeunload = () => {
window.scrollTo(0, 0);
};
to a function that calls window.scrollTo
method with the x and y coordinates of the page to scroll to as the page is being refreshed.
Conclusion
To force a page scroll position to the top at page refresh with JavaScript, we can use the window.scrollTo
method to scroll the page to the position we want in the beforeunload
event handler.