Placed in: Home arrow Programming arrow Webdesign arrow jQuery quickie: Unlimited Scroll using the Twitter API

Cialis Online

jQuery quickie: Unlimited Scroll using the Twitter API

Time for another relatively simple jQuery tutorial, just like my previous jQuery quickie. At work, I'm currently working with Silverlight and implemented unlimited scroll. This is a great technique that could be used on loads of websites. Instead of the regular pagination, where the user has to click to see the next page, unlimited scroll automatically loads the next page when the user is at the bottom.

I wanted to take this technique and port it to another jQuery example. So the quickie for today is Unlimited scroll using jQuery. I've using the Twitter API to make the example, so you'll learn a little bit about JSON too.

Unlimited Scroll using the Twitter API

Simply check out the demo to see the first tweets from my Twitter stream. Scroll down to load more tweets and see the unlimited scroll in action.

Demo Unlimited Scroll using the Twitter API   Download Unlimited Scroll using the Twitter API

Of course, you can use this same technique for something else instead of loading tweets, for example for loading next blog posts etc. Now, let's take a look at how you can create this Twitter example.

HTML

Just for the purpose of the example and aiming the focus on the jQuery part, I've created the most simplistic and minimal HTML you'll need.

 
<div id="tweets">
   <!-- Tweets will get loaded from jQuery -->
</div>
<div id="overlay">
   <img src="images/ajax-loader.gif" />
</div>

The first division (#tweets) is placed as a container that will hold all the loaded tweets. The second one will function as the overlay with an AJAX loader, that'll be placed on top to indicate the request has been made.

Now to give this HTML some little bit of styling using CSS.

CSS

I've used (almost) the same CSS styling as my Unique website for your Twitter updates Reloaded example.

We're using an absolute positioned division, just to keep the focus on the jQuery. Take note on the overflow : auto property: This will show the scrollbar.

 
#tweets { position: absolute; left: 186px; top: 105px;
   width: 376px; height:350px; overflow:auto; }
#tweets p { font-size: 14px; margin-bottom: 10px; padding: 10px;
   color: #7a8a99; background: url("../images/transpBlue.png"); }

We're also styling the paragraphs that'll be placed inside the #tweets container. Those will get injected by jQuery.

Since we're using absolute positioning, we can easily place the overlay on top of the container.

 
#overlay { position: absolute; left: 168px; top: 87px;
   width: 408px; height:386px; background: url("../images/transpBlue_overlay.png"); }
#overlay img { position:relative; left:200px; top:189px; }

As you can see, the image has been placed in the center of the container.

Nothing really exiting going on over here, but now comes the most fun part: the jQuery code!

jQuery

After loading jQuery and waiting for the document to be ready with loading, we can start the jQuery script. First, we'll need a couple of variables. As usual, comments are added to make some things clear.

 
// Set the size for each page to load
var pageSize = 15;
  
// Username to load the timeline from
var username = 'marcofolio';
 
// Variable for the current page
var currentPage = 1;

Now, we need to call a function that'll load the first page.

 
// First time, directly load the tweets
loadTweets();

The loadTweets() code is wrapped inside a function, since we'll need to call it over and over to load more tweets. This is how it looks like:

 
// Loads the next tweets
var loadTweets = function() {
   var url = "http://twitter.com/status/user_timeline/"
         + username + ".json?count="+pageSize+"&page="+currentPage+"&callback=?";
         
   $.getJSON(url,function(data) {
      $.each(data, function(i, post) {
         appendTweet(post.text, post.id);
      });
      
      // We're done loading the tweets, so hide the overlay
      $("#overlay").fadeOut();
   });
};

As you can see, we retrieve the Twitter timeline by calling the API and retrieving the current page from the user. The jQuery getJSON functionality retrieves the data, and iterates over all results (the each function). There, the appendTweet function is called with the text and id from the tweet (other data could be loaded too).

After we're done loading the tweets, we hide the overlay. But wait - we're calling a function appendTweet that doesn't exist (yet)! Yup, you're right, so here it is:

 
// Appends the new tweet to the UI
var appendTweet = function(tweet, id) {
   $("<p />")
      .html(tweet)
      .append($("<a />")
            .attr("href", "http://twitter.com/" + username + "/status/" + id)
            .attr("title", "Go to Twitter status")
            .append($("<img />")
               .attr("src", "images/link.png")
            )
      )
   .appendTo($("#tweets"));
};

We're using the jQuery function to dynamically the tweet paragraphs. We also add the link to the tweet by showing an image. We append the new element to the #tweets container and we're done!

But now, we have the initial fill (the first page). We now need to detect that the user is scrolling the #tweets container and find out if he is at the bottom to load the next page. Here's how this can be achieved:

 
// Append a scroll event handler to the container
$("#tweets").scroll(function() {
   // We check if we're at the bottom of the scrollcontainer
   if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
 
      // If we're at the bottom, show the overlay and retrieve the next page
      currentPage++;
      $("#overlay").fadeIn();
      loadTweets();
   }
});

Take note of the if condition to see if the user is at the bottom. When it is, the currentPage will get bigger, the overlay will fade in and the next tweets will get loaded.

That's all there is to it! I've added a little bit more code in the demo, which you can check out yourself if you download the source.

Conclusion and Download

Unlimited scroll could be great for user experience (so the example with the Twitter API would be useful), but when you think about SEO, it's not recommended. After all, a search engine spider doesn't actually scroll.

Demo Unlimited Scroll using the Twitter API   Download Unlimited Scroll using the Twitter API

What do you think? Should unlimited scroll be implemented more often? Or do you prefer the old skool technique? And do you see where you could improve the code? Feel free to share!


Tags:  scroll twitter jquery tutorial simple

Interested in this topic? You might enjoy another article I've written called

Did you like this article? Subscribe to my feed or email to keep updated on new articles.

Spread the word and submit to:
Digg!Reddit!Del.icio.us!Facebook!StumbleUpon!
Comments
Add NewSearchRSS
mufti - Nice tuts   2010-06-22 19:11:17
Gravatar image Nice tuts marco. Finaly I found this tutorial
Federica Sibella - Well done!   2010-06-23 06:16:34
Gravatar image Very nice example, since I'm diving into Twitter APIs it'll be very useful to me in the next weeks, thanks for sharing.
Jireck   2010-06-23 06:36:54
Gravatar image Excellent Marco
thanks
Beben - Prodigy of Head   2010-06-23 11:07:06
Gravatar image wow...its really unlimited, so long dude :lol:
thanks :)
Kivanc - Hashtag?   2010-07-02 17:38:07
Gravatar image Thanks for the tutorial Marco! Is it possible to do this with hashtag results instead of user tweets?
Waheed Akhtar - Very nice scroller   2010-07-06 05:45:10
Gravatar image Very nice scroller. I really liked it
Jeff Edsell - Very nice.   2010-07-08 14:36:51
Gravatar image Great tutorial. I love these short ones that get right to the point, and show you something really useful.

I understand all the code except:

Code:
$(this) [0].scrollHeight


I get that it returns the height of the scrollable area. But what does the [0] do?
Wechr - Great!   2010-07-08 19:54:16
Gravatar image Great tutorial, just what I needed for something I have to work on soon. Would be even better if it started to load a bit before reaching the bottom and you can avoid interrupting the user.
Mickey - Love It   2010-07-10 08:23:48
Gravatar image Great Idea
Very good idea to make as Social Networking is taking over the internet :lol:


Where do you get your ideas from :?: :?: :?:
Anonymous   2010-08-07 14:00:37
Gravatar image Great tutorial. I love these short ones that get right to the point, and show you something really useful.
Giacomo Colddesign - Very original post   2010-10-07 17:01:36
Gravatar image This is a very original use of jquery, thanks for posting it!
web tasar - very nice tutorial   2010-10-25 00:18:13
Gravatar image nice, thanks for sharing
Rho - perminantly loading   2010-12-10 20:59:07
Gravatar image I've been playing around with this on a local machine and it hangs frequently, just loads a lot of the time, whenever I check you demo version, it appears to be reflecting this. Is this a twitter issue, or are we both just hitting our API limits....
rho - yup   2010-12-10 21:44:35
Gravatar image as soon as I keep refreshing your demo, as soon as it starts hanging and gets stuck on loading, the same thing happens on my local machine. Looking at the code it can't be anything in there..does this mean that twitter is essentially underpowered server wise to the point that developing api like this is almost pointless as a solution until they expand their server capacity?
Raghib Suleman - a professional web designer and web developer   2010-12-22 08:23:30
Gravatar image Thanks for unlimited scroll plugin
Tim   2011-01-18 04:03:22
Gravatar image Is anyone working on turning this into a Joomla module?
Duong Truong - MovieXpress   2011-04-24 18:08:30
Gravatar image Thank for this perfect plugin, but i have to notice that when click the link to open twitter page it's show as 404 not found ;)
Berti - Add variables   2011-07-06 15:25:33
Gravatar image Everything runs smooth, but when I need to add more parameters to function appenTweets (created_at, profile_image_url) among others, cannot figure it out, i'm new to jquery and json and cannot land the way to add this parameters. I would thanks a lot if someone could give me the answer.
caterpuchi - instagram feed   2011-11-25 08:38:59
Gravatar image do you have any tutorial to use it on instagram feed? to scroll unlimited on the feed itself? thank you.
Ren - Bug with Code   2011-12-04 12:59:57
Gravatar image Actually, there is a bug associated with this code as I was testing it out. What happens when you reach the end of the last tweet? You did not exactly check for the case when the last tweets have been viewed. The unlimited scrolling should be stopped immediately and the users should be notified that they" had reached the end of the page" or some kind of a notification message.

This is not the case when it comes to the code. The currentPage variable is incremented all the time even when the last tweets have been reach. I manage to solve this by changing the code to this:

$.getJSON(url,function(data) {
$.each(data, function(i, post) {
appendTweet(post.text, post.id);
$("#pageCount";).html(currentPage);
$("#tweetCount";).html(currentPage * pageSize);
});

But the currentPage var is still being incremented although the number is not shown in the HTML page.

I guess I just have to code such functionality on my own. *sigh*
dolec - Link to twitter doesnt work   2011-12-05 19:32:11
Gravatar image nice tutorial however link to twitter is always the same and wrong.. maybe someone knows what to change
Read more...
Name:
Email:
  Gravatar enabled.
Website:
Title:
UBBCode:
[b] [i] [u] [url] [quote] [code] [img] 
 
 
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
 
Security Image
Please input the anti-spam code that you can read in the image.
Unsubscribe from e-mail notifications.
 
< Prev   Next >
Subscribe

7374 readers subscribed here. Subscribe today!