How do I scroll to the top of the page with JavaScript after the page is completely loaded.
Asked
Active
Viewed 128 times
-3
-
7[Read this](https://stackoverflow.com/questions/4210798/how-to-scroll-to-top-of-page-with-javascript-jquery). – sdgluck Sep 18 '15 at 16:03
-
You can use `window.scrollTo(x, y)` – PzYon Sep 18 '15 at 16:04
-
http://stackoverflow.com/questions/4210798/how-to-scroll-to-top-of-page-with-javascript-jquery – tkay Sep 18 '15 at 16:05
3 Answers
0
Use window.scrollTo(x, y)
where x
and y
are horizontal and vertical offsets in pixels.

isherwood
- 58,414
- 16
- 114
- 157

Mike Ezzati
- 2,968
- 1
- 23
- 34
0
var stepTime = 20;
var docBody = document.body;
var focElem = document.documentElement;
var scrollAnimationStep = function (initPos, stepAmount) {
var newPos = initPos - stepAmount > 0 ? initPos - stepAmount : 0;
docBody.scrollTop = focElem.scrollTop = newPos;
newPos && setTimeout(function () {
scrollAnimationStep(newPos, stepAmount);
}, stepTime);
}
var scrollTopAnimated = function (speed) {
var topOffset = docBody.scrollTop || focElem.scrollTop;
var stepAmount = topOffset;
speed && (stepAmount = (topOffset * stepTime)/speed);
scrollAnimationStep(topOffset, stepAmount);
};
And then:
<button onclick="scrollTopAnimated(1000)">Scroll Top</button>

iamdeowanshi
- 1,039
- 11
- 19