JavaScript: Force page position to top of page on browser refresh


If you had an instance where you wanted the site visitor to see your pages starting at the top, these quick snippets will do just that for you.

This is executed when the user leaves the page, which could be a page refresh or even clicking on a link to go to another page on the site.

Since the page would scroll to the top before you leave the page there maybe slight jerk that could be noticed.

Vanilla Javascript Solution:

The .scrollTo function accepts two parameters which are the X and Y Coordinates. Providing (0, 0) will refer to the pixel coordinate displayed in the upper left corner of the browser.

window.onbeforeunload = function () { 
   window.scrollTo(0, 0);

jQuery Solution:



Please enter your comment!
Please enter your name here