Jessica
Jessica

Reputation: 9830

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>

Upvotes: 37

Views: 73370

Answers (5)

Nishant Bhatt
Nishant Bhatt

Reputation: 589

For some reason, removing 'height: 100%' from my html and body tags fixed this issue.

Upvotes: 18

kadet
kadet

Reputation: 559

Removing overflow: hidden from my html tag fixed this for me.

Upvotes: 1

Slobodan Draksimovic
Slobodan Draksimovic

Reputation: 107

I found a simplest way to do this by adding eventListener to window object this way:

window.addEventListener("click", () => {
     let value = window.scrollTop;
     console.log(value);
});

This isn't the cleanest way, but It's the only way I got it work as it should.

Upvotes: -2

pusle
pusle

Reputation: 1523

I am not sure why, but the only thing I could get to work was using window.pageYOffset:

window.addEventListener('scroll', function() {
  let scrollPosition = window.pageYOffset;
  if (scrollPosition >= 30) {
    headerContainer.classList.add('lg:bg-green-lightest');
  } else {
    headerContainer.classList.remove('lg:bg-green-lightest');
  }
});

Upvotes: 12

Jessica
Jessica

Reputation: 9830

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;

Upvotes: 31

Related Questions