scrollTop (And a Little bit of offsetTop)
scrollTop
is an element property that gets or sets the top position (vertical scroll position) of the selected element. scrollTop
measures the distance from a) the top of the element to b) the element’s topmost visible content.
If there is no scrollable content, then the scrollTop
value is 0
. To better understand this, here’s an example.
You have an <article>
tag with several <p>
tags inside. Let’s say the <article>
is given a height of 100px and the text inside the article is fairly long so it overflows out. If you set <article>
to overflow-y: scroll
, you’ve given this element scrollable content/ability to scroll. As a result, JavaScript can return a scrollTop value greater than 0
.
Many times, the elements we select may not be scrollable. I’ve carelessly asked for the scrollTop
position of an element and it would always return 0
. In this case, I have to use element.offsetTop — document.body.scrollTop
.
offsetTop
returns the distance of the selected element relative from the top of the closest parent element. Going back to the example I used earlier, if <article>
’s closest parent element is <body>
, then offsetTop
will return the distance between the top of <body>
and the top of <article>
. This value will always be the same value value regardless of the scroll event. So subtracting that value from document.body.scrollTop
will give you the top position of <article>
relative to the window (or the element you’re listening on).
scrollTop
seems to be used most frequently used (and works with) document.body
and document.documentElement
because it’s very likely to assume that your <html>
and <body>
elements have scrollable content. Therefore, I find it safe to use document.body.scrollTop
and document.documentElement.scrollTop
. While we’re here, let me talk about the differences between the two.
document.documentElement
consists of the <html>
element and document.body
consists of the <body>
element. The talk online seems to confirm with me that document.body.scrollTop
is deprecated for Chrome in Strict Mode. That’s why developers fall back on the logical OR operator. document.body.scrollTop || document.documentElement.scrollTop
.
I have an example here where I use document.documentElement.scrollTop
to create a scroll progress indicator thingy. Not sure if there’s a technical term for that yet. But it’s a fixed <div>
at the top of the page that “fills” in from left-to-right based on the percentage the user has scrolled. Since both the <html>
and <body>
elements are scrollable, scrollTop
returns a value.
pageYOffset & scrollY
pageYOffset
is a read-only window property that returns the number of pixels the document has been scrolled vertically. And scrollY
is the exactly same thing. The main difference is that there is better cross-browser compatibility for pageYOffset
than scrollY
so it’s safe to just stick with pageYOffset
. But note that neither is supported in Internet Explorer < 9.