I need to detect that a user has scrolled to the bottom of a scrollable div. I assumed that the code below should work fine, and it does on a desktop computer, but not on a mobile device (Android, Chrome browser in this case).
var scrolledToEnd = el.scrollHeight - el.scrollTop === el.clientHeight
The scrollable div has overflow set to auto. It's clientHeight is 150px.
Desktop outcome when scrolled to bottom
el.scrollHeight - el.scrollTop is 150el.clientHeight is 150Mobile outcome when scrolled to bottom
el.scrollHeight - el.scrollTop is 149.90476el.clientHeight is 150Why is the outcome on a mobile device different? Is there a way to make this work on mobile as well? I haven't come up with an solution so far.
Hope someone can help, thanks in advance.
You could use
var scrolledToEnd = el.scrollHeight - Math.round(el.scrollTop) === el.clientHeight;
If you read the MDN you will notice
On systems using display scaling,
scrollTopmay give you a decimal value.
See this answer: https://stackoverflow.com/a/55029780/349604
Need to do a combination of rounding the scrollTop value and listening to resize events as well as scroll.
Be aware that (on Android browsers at least) clientHeight doesn't seem to respond to resize events, but window.innerHeight does (though on Android Chrome only after scrolling stops...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With