Mike Rifgin
Mike Rifgin

Reputation: 10761

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?

Upvotes: 151

Views: 318331

Answers (6)

Daniel Smerghetto
Daniel Smerghetto

Reputation: 1

For website worked for me document.getElementById("wrapwrap").scrollTo(0,0)

Upvotes: 0

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) {
        this.scrollTop = y;
        this.scrollLeft = x;
    },
    enumerable: false
});

Object.defineProperty(HTMLElement.prototype, "scrollBy", {
    value: function(x, y) {
        this.scrollTop += y;
        this.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 :-).

Upvotes: 63

Nick Craver
Nick Craver

Reputation: 630597

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

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

Upvotes: 241

dakab
dakab

Reputation: 5885

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);

Upvotes: 2

maxime schoeni
maxime schoeni

Reputation: 2877

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

Upvotes: 6

annakata
annakata

Reputation: 75872

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

Upvotes: 61

Related Questions