Displaying Your Tweets On Your Website With jQuery

Today we’re going to be back with our good old friend, jQuery. What we’re going to be doing is something that has become almost part-and-parcel of any website, especially a portfolio/blog site for individuals, which is to display your most recent tweets. Today we’re going to look at how easy jQuery makes this process. Of course, when using Javascript, there is a chance the user has it turned off, but for most people they will see a nice list of tweets. Beware, I am presuming you have an intermediate knowledge of jQuery.

Today we’ll write the code and package it up into a neat little, reusable function. Check out the Demo before we get started. In a future tutorial, we will look at converting it into a jQuery plugin.

Include jQuery

So, firstly, we will add jQuery to head of our page. By now you should be pretty comfortable doing this. I always use Google’s CDN:

	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

And now you want to add some blank script tags in which will go our code.

<script type="text/javascript" charset="utf-8">
	//code goes here
</script>

When Ready

Of course, we only want this code to run once the DOM is loaded. jQuery has its own ready function to make sure this happens:

$(document).ready(function() {
		//code goes here
});

Most of you will probably know that, however what many don’t realise is that we can shorten it:

$(function() {
	//code goes here
});

There is no speed benefit to using either, and if you prefer the first, it’s fine to use it.

Set up the HTML

Don’t worry, we’re nearly onto the fun bit! My HTML looks like so:

<div id="tweets">
		<h3 id="error">There was a problem fetching tweets</h3>
		<h3 id="preload">Currently loading your tweets...</h3>
	</div>

I have two headings, one with an id of “error”, and the other with id “preload”. With CSS, I hide the “preload” heading, so that when the user loads the page, only the first heading (the “error”) is shown.

This is where we can get sneaky – with jQuery, the first thing we’ll do is get rid of the “error” heading, and display the “preload” heading. It’s really easy:

$('#error').remove();
$('#preload').show();

The idea here is that if Javascript is not on, none of that happens and the user just sees the error. If it is on (and consequently we will go ahead fetching the tweets) then the user gets the preloading header.

Fetching your Tweets

The first thing we’re going to do is create an unordered list which we will put our tweets in:

var html='<ul>';

Next up is the fun bit. Getting your tweets. We’re going to use JSON (Javascript Object Notation). You can find out more about it at json.org. For the most part however, you don’t need to worry about how it works. You’ll find most sites support the fetching of data via JSON, including Twitter.

The URL to fetch your data looks like this:


http://twitter.com/status/user_timeline/Jack_Franklin.json?count=5&callback=?

There are two bits we can change there. The first obviously is the username. Mine is “Jack_Franklin”, but if you wanted your own, replace “Jack_Franklin” with your id. (Later on in this article we will make this a lot easier). The second bit to change is the section “count=5″. This sets the number of tweets to return.

You may wonder about the final part “&callback=?”. This page at Clientcide explains it well.

JSONP is a means by which to get JSON data from another domain than the one your page is on. If you try and use Ajax to request data from a different domain than the page, you’ll get a security error.

Essentially, without that bit, we could not request data from a domain other than our own. Remember earlier, when I said you don’t need to worry about how it works? This is an example of that.

$.getJSON

We’re going to be using the jQuery function getJSON(). getJSON is not really a function in its own right, it acts as a wrapper for $.ajax(), but makes things much simpler for us. getJSON takes two parameters:

$.getJSON(feed url, callback function)

We’ve already got our feed URL, so lets save it to a variable, pass it in and then set up our function:

var tweetFeed = 'http://twitter.com/status/user_timeline/Jack_Franklin.json?count=5&callback=?'
$.getJSON(tweetFeed, function()
{
});

Our callback functions needs to be passed the data that was returned, so that we can use it from within the function. You might think this is going to be really complex, but it’s not. We’re going to pass in a variable and this variable will contain the data. This variable can be called anything, jQuery does the rest. I tend to call mine “d” for “data”. You can call it “data” if you wish to be more verbose. It’s up to you. Call it “chicken” if you like. Our appended function looks like so:

$.getJSON(tweetFeed, function(d)
{
});

Process!

So, for each item, we need to process it. The data returned is an object that we can loop through using jQuery’s each() method:

	$.each(d, function(i,item)
				{

				})

So jQuery’s each() function takes two paramters – the data we want to iterate for (which in our case is the variable d, containing our data), and the second is a function to run. Our function looks like this:

function(i, item) {..}

Here i is the iteration variable, every time you loop through the data i gets increased. The second is a variable each item will be passed to through the iterations. So on our first loop, item contains the value of the very first item. On our next iteration, it contains the value of the second, and so on. Each item contains lots of data, the below text is all the data the very first returned tweet contains:

{"in_reply_to_status_id":null,"in_reply_to_screen_name":null,"contributors":null,"place":null,"favorited":false,"source":"<a href="http://twitter.com" rel="nofollow">Tweetie for Mac</a>","geo":null,"coordinates":null,"user":{"following":true,"description":"jQuery is my cocaine.","listed_count":47,"statuses_count":8833,"profile_use_background_image":true,"profile_background_color":"352726","show_all_inline_media":false,"followers_count":781,"contributors_enabled":false,"profile_background_image_url":"http://a3.twimg.com/profile_background_images/13458527/bg.jpg","profile_text_color":"3E4415","profile_image_url":"http://a1.twimg.com/profile_images/400484737/Photo_2-1_normal.jpg","friends_count":603,"profile_background_tile":false,"profile_link_color":"D02B55","url":"http://www.jackfranklin.co.uk","screen_name":"Jack_Franklin","geo_enabled":false,"notifications":false,"time_zone":"London","favourites_count":4,"protected":false,"follow_request_sent":false,"lang":"en","created_at":"Sun Apr 06 09:31:28 +0000 2008","profile_sidebar_fill_color":"bec1bd","location":"Cornwall, England","name":"Jack Franklin","verified":false,"id":14314572,"utc_offset":0,"profile_sidebar_border_color":"ffffff"},"in_reply_to_user_id":null,"truncated":false,"created_at":"Sun Aug 08 21:15:57 +0000 2010","id":20655130616,"text":"Anyone figure when us subscribers are due a new .Net mag ?"}

Accessing the Data

So we know that all that data is passed to the item variable, but how do we access the individual items? The main one you will want to look for is the property “text”, which contains the tweet. We access this using the dot notation, like so: item.text; So, in our loop, we’ll just add each item to our unordered list, which we created way back at the beginning.

	$.each(d, function(i,item)
				{
					html+='<li>'+item.text+'</li>';
				})
				html+="</ul>";

And once the loop is over, we’ll round off our list with the closing tag. So, we now have a nice list, full with our five most recent tweets.

Displaying the Tweets

Finally we must display the tweets, and this is the code that does it:

$('#tweets').children('h3').fadeOut('fast',function() {

					$('#tweets').append(html);
				})

The code is very straight forward, firstly we find all the headers and fade them out, so our “tweets” div is empty. Once those headers are faded out, we run a callback function which adds our HTML to our twitter div.

All Done!

Congratulations! You can now display your tweets using jQuery. But there’s one more bit. We’re going to wrap this up in a function and next time, we will convert it into a plugin.

This is what I’ve done:

function showTweets(elem, username, number)
	{
		var html = '<ul>';

	var tweetFeed = 'http://twitter.com/status/user_timeline/' + username + '.json?count=' + number + '&callback=?'
		$.getJSON(tweetFeed, function(d)
		{

			$.each(d, function(i,item)
			{
				html+='<li>'+item.text+'</li>';
			})
			html+="</ul>";

			elem.children().fadeOut('fast',function() {

				elem.append(html);
			})
		})
	}

There’s a couple of changes – firstly, we pass in the element, username and the number of tweets we want to display. We all hide all the given element’s children, so we can make sure it’s completely blank before passing in the tweets (this is something we will certainly be improving when we make this into a plugin). The function is used like so:

	showTweets($('#tweets'), 'Jack_Franklin', 5)

Next time, as I said, we will make some changes and wrap this up as a jQuery plugin which is much better to reuse than a function, in my opinion. I’ll also post the plugin for download so you can use it in your own tweets.

A DEMO can be downloaded here.

15 Comments on "Displaying Your Tweets On Your Website With jQuery"

  1. Beben says:

    wheres the demo…:D

  2. Beben says:

    nice …:)
    it would be great if there rolling effect…;)
    thanks so much for added the demo :)

  3. Thanks for u r information

    its very useful

  4. Alan says:

    Love this tutorial, alot more in depth to actually teach people Javascript.

    Thanks.

  5. Ted Thompson says:

    Great article! Very helpful. Thanks for sharing.

  6. Amy Lo says:

    Love this!
    By the way, we can also add some markup for the @, # and links to the Tweets. I wrote up a quick js function for this:

    function addLinks(tweet){
    /*
    Takes the plaintext Tweet and returns it with the links for @ and # and http://
    Converts the string to array delmited by the space character, looks at each piece and parses accordingly
    */
    var newTweet = “”;
    var splittedTweet = new Array();
    splittedTweet = tweet.split(” “);
    var tokenTweet;

    var i = 0;
    var n = splittedTweet.length;
    while (i 1) {
    // Look for @ and add the twitter link for user
    if (tokenTweet.indexOf(“@”) == 0){
    tokenTweet = tokenTweet.link(“http://twitter.com/”+tokenTweet.substr(1));
    }
    // Look for # and add the twitter link for searching tags
    if (tokenTweet.indexOf(“#”) == 0){
    tokenTweet = tokenTweet.link(“http://twitter.com/search?q=”+tokenTweet.substr(1));
    }
    if (tokenTweet.indexOf(“h”) == 0 && tokenTweet.substring(0,7) == “http://”){
    tokenTweet = tokenTweet.link(tokenTweet);
    }
    }
    newTweet += tokenTweet+” “;
    i++;
    }
    return newTweet;
    }

    Just call this function on the line in showTweets(), where it was Accessing the Data: html+=”+item.text+”;
    change it to : html+=”+addLinks(item.text)+”;

  7. Jack Franklin says:

    Hey everyone,

    Glad you liked it!

    @Amy Lo – thanks for writing that – that is part of what’s planned in the next tutorial, you beat me too it ;) I’ve done it a different way, using Regular Expressions, but your way would work just as well. Thanks for the contribution.

    Jack.

  8. Husyn says:

    Apart from very good article, way of showing everything is ‘alaa’ Great!

  9. Va Infotech says:

    Cool J Query

    thanks Dear

  10. anonymous says:

    Thanks for this tutorial. But how can I show the date of each tweet ?

  11. envirse says:

    any reason why the tweats would show up twice in safari and chrome? http://www.envirse.com
    set the value to 1 from 5.

    thanks.

  12. Thanks for the nice information. I am sure, I will tweet this to my twitter account. This will help a lot of users.

Got something to say? Go for it!