-3

How do I scroll to the top of the page with JavaScript after the page is completely loaded.

3 Answers3

0

Try:

document.body.scrollTop = document.documentElement.scrollTop = 0;
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