I'm trying to find the vertical position of the scrollbar a function similar to jQuery's scrollTop() but with no jQuery. Are there any alternatives?
Asked
Active
Viewed 2.7k times
24
-
Isn't [element.scrollTop](https://developer.mozilla.org/en/DOM/element.scrollTop) sufficient? – Marat Tanalin Jun 25 '12 at 16:50
-
1just read the source of jQuery's scrollTop(): https://github.com/jquery/jquery/blob/master/src/offset.js – snies Jun 25 '12 at 16:52
3 Answers
47
Cross-browser solution:
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
var scrollLeft = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
var scrollTop = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

Engineer
- 47,849
- 12
- 88
- 91
-
I think this should be accepted as an answer. The solution in the accepted answer is not cross-browser. – dragn Jul 02 '12 at 11:27
-
very little syntax correction: the comma at the end of the first row will generate an error - take care – Marco Panichi May 19 '15 at 10:49
16
Yes, the scroll position exists within the DOM at:
window.scrollY; //for vertical scroll.
How I found this:
- In Chrome, right click and select Inspect Element.
- Find and click the 'Show Console' button (lower-left)
- In the console type window.scroll to see options.
-This is an exceptional workflow to solve a multitude of JavaScript questions.
I see window.scrollTo(0) as an option to scroll to top.

Nash Worth
- 2,524
- 1
- 21
- 28