Categories
JavaScript Answers

How to force page scroll position to top at page refresh in HTML with JavaScript?

Spread the love

To force page scroll position to top at page refresh in HTML with JavaScript, we add a beforeunload event handler.

For instance, we write

window.onbeforeunload = () => {
  window.scrollTo(0, 0);
};

to set window.onbeforeunload to a function that calls window.scrollTo with 0 and 0.

Then right before the page is refreshed, the function is called to scroll the page to the top.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *