Published: April 20 2013

Enable infinite scroll on iPhone and desktop with jQuery

There seems to be quite a few code examples out there for jQuery infinite scroll for iPhone that simply don't work, now maybe this is because the older versions of iOS behave differently but that seems unlikely for something as basic as measuring $(window).scrollTop(), $(window).height() and  $(document).height(). 

I haven't bothered testing this example across a bunch of different iOS versions, but I can tell you that it definitely works on iPhone iOS 6.0.1 and desktop browsers. 

There are just two pieces of code you need to get it working:

  1. The viewport meta tag, making sure you include height=device-height, without this it won't work in iPhone
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0" />
  2. This snippet of jQuery to detect when the user has scrolled to the bottom of the page
    // enable infinite scroll
    $(document).scroll(function () {
        var triggerScroll = $(window).scrollTop() + $(window).height() >= $(document).height();
        if (triggerScroll) {
            if ($(".more_link a").length) {
                $(".more_link a").click();
            }
        }
    })

In this example I'm clicking a link to display more items, but you can do whatever you like when the event is triggered. I have a link there on the off chance that the infinite scroll doesn't work so the user can still click the "more" link to view more items. It's taken directly from my travel blog site so you can see the working example at www.whateverworks.net.au.

 


Need Some HTML5 Help?

Search fiverr for freelance HTML5 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by