Search code examples
javascriptdom

element.scrollTop always returns 0


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>


Solution

  • 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;