How to get scrollbar position with Javascript? How to get scrollbar position with Javascript? javascript javascript

How to get scrollbar position with Javascript?


You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.


I did this for a <div> on Chrome.

element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element.scrollHeight - is the pixels of the whole div.

element.clientHeight - is the pixels that you see in your browser.

var a = element.scrollTop;

will be the position.

var b = element.scrollHeight - element.clientHeight;

will be the maximum value for scrollTop.

var c = a / b;

will be the percent of scroll [from 0 to 1].


document.getScroll = function() {    if (window.pageYOffset != undefined) {        return [pageXOffset, pageYOffset];    } else {        var sx, sy, d = document,            r = d.documentElement,            b = d.body;        sx = r.scrollLeft || b.scrollLeft || 0;        sy = r.scrollTop || b.scrollTop || 0;        return [sx, sy];    }}

returns an array with two integers- [scrollLeft, scrollTop]