[javascript] Set scroll position

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?

This question is related to javascript

The answer is


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

window.scrollTo(0, 0); // values are x,y-offset

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

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


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 :-).