145

I'm trying to set the scroll position on a page so the scroller is scrolled all the way to the top.

I think I need something like this but it's not working:

(function () { alert('hello'); document.body.scrollTop = 0; } ());

Any ideas?

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111

5 Answers5

231

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset
Owaiz Yusufi
  • 849
  • 1
  • 14
  • 34
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
60

Also worth noting window.scrollBy(dx,dy) (ref)

annakata
  • 74,572
  • 17
  • 113
  • 180
57

Note that if you want to scroll an element instead of the full window, elements don't have the scrollTo and scrollBy methods. You should:

var el = document.getElementById("myel"); // Or whatever method to get the element

// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;

// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;

You can also mimic the window.scrollTo and window.scrollBy functions to all the existant HTML elements in the webpage on browsers that don't support it natively:

Object.defineProperty(HTMLElement.prototype, "scrollTo", {
    value: function(x, y) {
        el.scrollTop = y;
        el.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        el.scrollTop += y;
        el.scrollLeft += x;
    },
    enumerable: false
});

so you can do:

var el = document.getElementById("myel"); // Or whatever method to get the element, again

// To set the scroll
el.scrollTo(0, 0);

// To increment the scroll
el.scrollBy(100, 100);

NOTE: Object.defineProperty is encouraged, as directly adding properties to the prototype is a breaking bad habit (When you see it :-).

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64
7

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;
maxime schoeni
  • 2,666
  • 2
  • 18
  • 19
  • I like this solution over the selected one more, as 1. It is more inline with what OP wanted to do in the first place, 2. Also allows reading the value of the scroll position – Pandaiolo Sep 01 '23 at 10:26
2

If you want to set the scroll position of document.body, you can scroll the entire window altogether using window.scrollTo(); it takes either a pair of coordinates (x,y) or an options object – if you just want to scroll nicely to the top, try window.scrollTo({top:0,behavior:'smooth'});.

However, in some instances, you have an element to scroll (and not the entire document). For that case, elements also provide a scrollTo() method using the same arguments.

document.querySelector('ul#list').scrollTo(0,0);
dakab
  • 5,379
  • 9
  • 43
  • 67