Vanilla JavaScript: Scroll to Top of Page

Manngo picture Manngo · Sep 15, 2017 · Viewed 14.5k times · Source

I may have missed something, but I cannot get window.scrollTo(0,0) to move to the top of the page.

I am implementing a sticky aside which works well enough. It uses .getBoundingClientRect() to get the initial position.

However, if the page is partly scrolled, and I refresh the page, it reads the position wrongly, and is positioned in the wrong place.

I though I would fix this by executing window.scrollTo(0,0) at the beginning, so that the page is at the top, and the aside is in the right position.

When I run the code, window.scrollTo(0,0) doesn’t seem to make any difference.

What is the correct way to get the reloaded window to start at the top?

I have tested it on Firefox on the Mac. Chrome and Safari gives a similar behaviour.

Please, no jQuery.

Answer

TKoL picture TKoL · Sep 15, 2017

Have you tried waiting for page load before scrollTo? Try using window.onload

window.onload = function(){
    window.scrollTo(0,0);
}