24

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?

ama2
  • 2,611
  • 3
  • 20
  • 28

3 Answers3

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;

source

Engineer
  • 47,849
  • 12
  • 88
  • 91
16

Yes, the scroll position exists within the DOM at:

window.scrollY;  //for vertical scroll.

How I found this:

  1. In Chrome, right click and select Inspect Element.
  2. Find and click the 'Show Console' button (lower-left)
  3. 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
8

scrollX and scrollY.... scrollY is the equivalent of jquery scrollTop()

Trey
  • 5,480
  • 4
  • 23
  • 30