plainJS

Functions / Styles

Get and set scroll position of an element

jQuery $.scrollLeft(), $.scrollTop()

2015 page

This is the original page from 2015, kept at its address while the tested rewrite is in progress. The code is of its time: it ran in Internet Explorer and does not use what browsers have gained since. The rewrite replaces it here.

In short

Get or set the horizontal and vertical scroll position of an element or the document.

Use the properties scrollTop and scrollLeft to get or set the scroll position of an element:

js
var el = document.querySelector('div');

// get scroll position in px
console.log(el.scrollLeft, el.scrollTop);

// set scroll position in px
el.scrollLeft = 500;
el.scrollTop = 1000;

Getting the scroll position of the document in px.

js
var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Setting the document scroll position of the document in px:

js
document.documentElement.scrollTop = document.body.scrollTop = 1000;
document.documentElement.scrollLeft = document.body.scrollLeft = 500;