Recently I was asked to include an infinite scroll for a client’s twitter account on their homepage. I was surprised at how easy it turns out to be.
In a nutshell, it consists of:
Use AJAX to hit Twitter’s timeline API to get the tweets
Use JQuery to detect when the user is scrolling
Use a little bit of maths to figure out when to trigger another page of tweets
First, we add a link to grab JQuery from the Google CDN.
Next, add in placeholders for the tweets
1 2 3
Now the call to get the tweets from Twitter and add them as items to our list (I’m using Stephen Fry as the test subject as he tweets LOADS):
1 2 3 4 5 6 7 8 9 10 11 12 13
Note that we are passing in the page number. This is important for the next few bits.
Now we add the JQuery to load the page on opening.
1 2 3
For the infinite scroll, we need to do a few things. First, we need to be able to pass the next page to Twitter’s API so we need a mechanism to store it. We can use a HTML5 data item to do this:
Next, we need a nextPage function to get and set this value as well as call the getPagedTweets function we already have:
1 2 3 4 5
Finally, we need the JQuery to trigger an event when the user scrolls to the bottom of the page:
1 2 3 4 5 6 7 8
And that should be that.
Note the page should be resized to ensure that scrollbars are visible otherwise this will not work as the user needs to scroll in order for the next page call to work.