Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to force page scroll position to top at page refresh in HTML with JavaScript.

In this article, we’ll look at how to force page scroll position to top at page refresh in HTML with JavaScript.

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

To force page scroll position to top at page refresh in HTML with JavaScript, we scroll the page to the top when the beforeunload event is triggered.

For instance, we write

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

to set window.onbeforeunlod to a function that runs when we refresh the page.

In it, we call scrollTo with 0 and 0 to scroll to the top of the page when we refresh.

Conclusion

To force page scroll position to top at page refresh in HTML with JavaScript, we scroll the page to the top when the beforeunload event is triggered.

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 *