7

I've found the classic MDN formula to check if content has been scrolled to the bottom,

element.scrollHeight - element.scrollTop === element.clientHeight

doesn't work for all cases any more. For example, if you change the scale of content to something bigger than 100% for the demo page on MDN you will not get the right result. This happens because now browsers use subpixel precision on elements. Particularly scrollTop for not 100% scale is a fractional value now. Actually the problem happens because of === sign in the formula above.

So what is the simplest, but still reliable, solution?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
  • 1
    This also happens on any displays with devicePixelRatio not `1` causing CSS pixels to be scaled, even if the elements themselves are not scaled. – trusktr Feb 11 '22 at 19:54
  • 2
    Does this answer your question? [Check if a user has scrolled to the bottom (not just the window, but any element)](https://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom-not-just-the-window-but-any-element) – TylerH Mar 03 '23 at 18:38
  • For reference, the answer here by Konstantin (using Math.abs) exists on the canonical) – TylerH Mar 03 '23 at 18:38
  • (*"era"* does not appear to be a misspelling of *"area"*. It does appear to refer to time (evolution of web browsers over time).) – Peter Mortensen Apr 13 '23 at 09:15

2 Answers2

6

My current solution:

function isContentScrolledToBottom(element) {
    const rest = element.scrollHeight - element.scrollTop;
    return Math.abs(element.clientHeight - rest) < 1;
}

It checks if the element is scrolled to bottom with ±1 accuracy.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
  • @trusktr Problem with these solution is this also fires once when you scroll back up from bottom. – Toniq Nov 29 '22 at 12:55
  • @Toniq Yeah, I don't think there's a perfect solution. You may have to adjust the number `1` depending on other factors like zoom or scale. Do you have an example? Would be interesting to see your issue and see what we can do. – trusktr Dec 05 '22 at 02:03
0

This function triggers whenever you scroll, and then you can do something that you want to do.

  window.onscroll = function() {scrolled()};
  function scrolled() {
    fixed = document.body.scrollTop > 20 ||
    document.documentElement.scrollTop > 20 ?
      "Am Going Down" : "Am Going Up"
  }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Korak
  • 39
  • 8