I'm trying to get the scrollTop position of an element, but it always returns 0. What am I doing wrong, and how can I fix it?
var inner = document.getElementById('inner'); window.addEventListener('scroll', function() { console.log(inner.scrollTop); })
#outer { background-color: tan; height: 1000px; } #first { background-color: bisque; height: 200px; } #inner { background-color: aquamarine; height: 100px; }
<div id="outer"> <div id="first"></div> <div id="inner">scrollTop always returns 0</div> </div>
scrollTop()Returns: Number. Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .
To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
scrollTop is deprecated in strict mode.
As @FelixKling pointed out in the comments:
inner.offsetTop
is what to use for this. scrollTop
returns the amount you scrolled in that particular container. So because inner
doesn't have a scrollbar, it never scrolls, and therefore scrollTop
is 0.
But offsetTop
, on the other hand, returns the distance of the current element relative to the top of the offsetParent
node.
So the formula to get the amount scrolled of an element based on window
, would be:
inner.offsetTop - document.body.scrollTop;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With