Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.scrollTop always returns 0

Tags:

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?

JSFiddle

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>
like image 865
Jessica Avatar asked Dec 30 '16 06:12

Jessica


People also ask

What does scrollTop return?

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.

What is scrollTop value?

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 .

How do I get scrollTop value?

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.

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.


1 Answers

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; 
like image 117
Jessica Avatar answered Sep 17 '22 14:09

Jessica