Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if scrolled to bottom on mobile devices

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 150
  • el.clientHeight is 150

Mobile outcome when scrolled to bottom

  • el.scrollHeight - el.scrollTop is 149.90476
  • el.clientHeight is 150

Why 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.

like image 529
Camille Sébastien Niessen Avatar asked Dec 17 '25 14:12

Camille Sébastien Niessen


2 Answers

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, scrollTop may give you a decimal value.

like image 196
Gabriele Petrioli Avatar answered Dec 19 '25 04:12

Gabriele Petrioli


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...).

like image 24
James Nisbet Avatar answered Dec 19 '25 03:12

James Nisbet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!