element.scrollTop always returns 0

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

I hope this helps someone else!


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;

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');
  }
});

Tags:

Javascript

Dom