What’s the best way to use JavaScript scroll to top of page after a page reload?

I tried the following to make sure the page scrolls to the top after reloading, but it didn’t work as expected:

$('document').ready(function() {
$(window).scrollTop(0);
});

The issue seems to be that after a refresh, the browser scrolls to its previous position before executing the script. How can I ensure the page always scrolls to the top, even after a reload?

Well let me be very clear, instead of using jQuery or the ready event, you can listen for the load event, which fires after the page content has fully loaded. You can then call window.scrollTo(0, 0) to scroll the page to the top.

window.addEventListener('load', function() {
window.scrollTo(0, 0);
});

Actually, window.scrollTo(0, 0) scrolls the page to the top, and the load event ensures the script is run after all content has loaded. That’s all! Enjoy!! :grin:

Yo! Use jQuery with $(window).on(‘load’). It just that if you prefer to use jQuery, you can listen for the load event in jQuery, just as you would with plain JavaScript.

$(window).on('load', function() {
$(window).scrollTop(0);
});

The load event ensures the page content has finished loading, so you can safely scroll to the top. That is why it works.

I hope it helps! Thank you :innocent:

sing window.scrollTo() in the DOMContentLoaded event — this can be done too!

I know one more method which isn’t like the ones shared by @akanshasrivastava.1121 and @jacqueline-bosco. Try it once, you won’t regret it. At least I don’t :wink:

This behaves similar to the load event, but DOMContentLoaded triggers earlier, as soon as the HTML is fully parsed, before stylesheets, images, and subframes are loaded. It might be a more efficient solution if you don’t need to wait for images to load.

document.addEventListener('DOMContentLoaded', function() {
window.scrollTo(0, 0);
});

Basically, DOMContentLoaded ensures that your script runs as soon as the document’s HTML is ready, so the page scrolls to the top before other resources like images are loaded.