The goal is to detect the bottom of a page for an infinite scroll feature, such as those used for social media feeds. The solutions already suggested mostly involve something like:
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {...}
This works great on the desktop but on a mobile device, the bottom of the page isn't being detected consistently.
The following are examples just to get an idea of what is happening. Both cases are occurring when fully zoomed out on a test page but the actual numbers vary depending on whether a page is zoomed in or not.
- iPad Chrome: In landscape mode,
$(window).scrollTop() + $(window).height()
would consistently be about 15px shy of$(document).height()
- Galaxy S4 Chrome: In portrait mode,
$(window).scrollTop() + $(window).height()
would consistently be about 36px shy of$(document).height()
In both cases, if the user was to zoom in sufficiently (usually a little bit is enough) on the page and then scroll to the bottom, the bottom of the page was detected and the infinite scroll goodness occurs. Needless to say, it's not ideal to assume the user will zoom in to trigger the infinite scroll. Interestingly, detecting the bottom works fine on the iPad Safari.
I've tried different solutions, including a solution suggested in another post involving getDocHeight()
by James Padolsey to no avail. It didn't seem like James' solution would help because it looks like the problem is at $(window).scrollTop()
but I tried it anyway.
if ($(window).scrollTop() + $(window).height() >= getDocHeight()) {...}
A simple workaround is to just add a bit to the left side of the statement, e.g., 100. However, this seems like a cheap hack that could be easily broken by different devices/browsers so something a bit more robust is preferable.
if ($(window).scrollTop() + $(window).height() + 100 >= $(document).height()) {...}
Thoughts/suggestions? Thank you in advance!
Update I took the tip from @Pomax and ran with it. With https://stackoverflow.com/a/7557433/1634817 in hand, the infinite paging is working now. I ended up adding an element at the end of the page and every time that element is visible to the user, the next set of content is loaded.
Related StackOverflow questions: