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

Spread the love

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

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

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

To force page scroll position to the top at page refresh with HTML and JavaScript, we set the beforeunload property to a function that scrolls to the top of the page.

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 to scroll to the top of the page when the page is going to refresh.

Conclusion

To force page scroll position to the top at page refresh with HTML and JavaScript, we set the beforeunload property to a function that scrolls to the top of the page.

Leave a Reply

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