Scroll to page top on page refresh using javascript

On page reload,most of the browsers tend to restore the last scroll position.

The JavaScript ‘history’ API has the ‘scrollRestoration ‘property, which when set to manual , prevents the last scroll location on the page to be restored. We can use this property in the following way:

history.scrollRestoration = 'manual';

Before the page unloads, we can change the scroll position to the top of the page. This would change the browser’s last scroll position, and when the page refreshes it would start at the top of the page.

So javascript code to scroll to top of page on page reload is:

if (history.scrollRestoration) {
    history.scrollRestoration = 'manual';
} else {
    window.onbeforeunload = function () {
        window.scrollTo(0, 0);
    }
}

Leave a comment

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