23
Jul
2009
26
Display your latest Twitter update with jQuery
UPDATE: May 2010 – There is now a new updated blog article that follows on from this article. Once you have finished reading this, please read part 2.
I’m pretty sure that it has not escaped your attention that Twitter is an invaluable tool if you want to communicate with your clients and peers. As you are spending all this time tweeting, it makes sense to display this information on you own website so you can draw in more followers on Twitter and get your voice heard.
There are quite a few tutorials available on this subject and several jQuery plugins that will display your tweets for you, all of which are very good in their individual way. However, this tutorial will show you just how easy it is to use the Twitter API tools with a tiny bit of jQuery to display your latest tweets in a fully customisable, simple and functional way.
First we will create a very basic HTML document to display our latest tweet. Then I will show you how to get the Twitter JavaScript code which will translate the returned data for us. We will be using our Twitter account, @carronmedia in the examples, please feel free to follow us.
The Twitter API
The nice people over at Twitter have provided us with a selection of tools, know as API’s, that allow us to easily use and update information on their servers. For this tutorial, we are going to concentrate on the most basic of these functions which is to simply retrieve the latest tweet for a selected Twitter account. There is an API for pretty much any programming language and plenty of documentation to back it up. Head over to the Twitter API Wiki where you will find all the information you need.
Why bother using jQuery?
Although Twitter is a wonderful service, it can suffer time to time from a bit of overcrowding and as a result, their servers can be a bit slow in returning data to your website. This can cause undesirable problems with your site and prevent the other data on the page from downloading.
We can reduce these problems by using the jQuery $(document).ready() method to load the our modified JavaScript file after the DOM has loaded and also allows to to give the end user some feedback (in the form of an loading .gif image) to let them know that some data is on its way.
The basic HTML
Create a new file in your project and call it index.html. Open it up and enter the following:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My latest Tweet</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> <script src="twitter.js" type="text/javascript"></script> </head>
This is standard XHTML document so we have specified a DOCTYPE and a page title. The first thing we need to do is load the jQuery library. This is best achieved by loading the core file from a content delivery network such as Google’s. I have gone into more detail about this in a previous post, Extend Google Analytics with jQuery, so I won’t go into it again here.
We have also referenced a bespoke JavaScript file called twitter.js which we will create shortly. Make sure you get your folder path correct. For example, if you create your twitter.js is a sub-folder called ‘js’, the src attribute will become src="js/twitter.js".
Create a loading image
Before we continue, head over to ajaxload.info which, if you have never seen this before, is a great site where you can easily create a nice loading animated .gif file. Choose your design, or download the project source code and use the one I generated.
Now lets create the body of the html file. Here we will create a <div> element that will insert our tweet into. Also, there is a nested div within it that will hold our nice animated gif that lets the end user know that something will be loaded into this area.
Enter the following at the end of the file:
<body>
<div id="latest_tweet">
<h3>Twitter</h3>
<div class="loading"></div>
</div>
<a href="index.html">Reload</a>
</body>
</html>
There isn’t too much explanation need for this markup. The <div> with a class of ‘loading’ will have our loading .gif as a background image and will be faded out once our tweet has been successfully loaded.
Style the tweet
Finally we need to style this markup, add the following in the <head> section beneath the last <script> tag (in a real live project, you should create these styles in a separate .css file):
<style type="text/css">
body {
font: 12px/16px normal Arial, Helvetica, sans-serif;
color: #666;
}
#latest_tweet {
border: 1px solid #dfdfdf;
width: 250px;
padding: 20px;
}
#latest_tweet small, #latest_tweet a {
color: #7aa6cb;
}
.loading {
background: url('ajax-loader.gif') center no-repeat;
height: 60px;
}
</style>
Again, if you put your .gif file in a different folder, make sure you change the path to it in the styles.
Creating our Twitter JavaScript file
First of all, we need to create a local copy of the Twitter code that will translate and format the JSON data. Go to your Internet browser of choice and enter http://twitter.com/javascripts/blogger.js. Depending on your browser, you will be shown the file in plain text or prompted to download it. Either way, save a copy of it into your project folder and call it twitter.js.
Open up your twitter.js file and you should see two functions, twitterCallback2 and relative_time. The twitterCallback2 function will translate the JSON data that we will request with jQuery and output it HTML and the relative_time function will format the time.
Lets start to modify the original code. Look for the follow line in the twitterCallback2 function:
statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
and replace it with this line:
statusHTML.push('<p>“'+status+'” – <small>'+relative_time(twitters[i].created_at)+'</small></p>');
The original code will output a list item tag (<li>), which seems a little pointless as we are only going to display one tweet. So we have replaced it with <p> tags and reformatted the HTML a little bit.
Next, delete the following line at the end of the twitterCallback2 function:
document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
and in its place type:
$('.loading').fadeOut(750, function() {
$('#latest_tweet').append($(statusHTML.join('')).hide().fadeIn(750));
});
This jQuery code will fade out the placeholder <div> which contains the loading image and then fade in our latest tweet in it’s place.
Finally, at the very end of the twitter.js file, type the following (make sure you change the username variable to the Twitter account who’s latest tweet you are going to display):
$(document).ready(function() {
var username = 'carronmedia';
$.getScript('http://twitter.com/statuses/user_timeline/' + username + '.json?callback=twitterCallback2&count=1');
});
This uses the jQuery getScript method to load the Twitter API script that will return our tweet. To break this down a little bit, the twitter API will accept a few different arguments to be appended to the end of the file which we are loading. The first argument we require is called callback. This refers to the name of the function that we want to load the returned JSON data into. In our case, the callback argument is equal to the name of the first function in our twitter.js file. The second argument, count, simply tells the Twitter API how many tweets to return. In our case, this is set to 1.
Conclusion
UPDATE: May 2010 – There is now a new updated blog article that follows on from this article. Once you have finished reading this, please read part 2.
Twitter is a fabulous marketing tool and can really help you communicate with your end users on your site. Having the ability to automatically display your latest tweet really helps visitors relate to you as a person. It is also a handy little way of showing that your site is active and there is a real human being behind it.
Have you extended this code further? Do you think that there are other uses for this technique? Perhaps you have written your own jQuery plugin with it. Please comment below and let us know, we would love to hear if you have found this useful in any way.
Thanks!

26 Responses to “Display your latest Twitter update with jQuery”
Comments
July 26th, 2009 at 12:07 pm
I was just looking at doing something similar for my site. Thanks for this!
July 26th, 2009 at 12:20 pm
Nice and simple, won’t have to use a plugin for this anymore, and thanks for the pointer to ajaxlaod.info – will definitely use this a lot.
July 27th, 2009 at 3:40 pm
Thanks for the clear instructions. Sweet!
August 4th, 2009 at 5:50 am
thanks, great tutorial. awesome technique!
September 14th, 2009 at 8:04 pm
very helpful tutorial! thanks a ton!
October 20th, 2009 at 9:22 am
thanks for the great script..
January 10th, 2010 at 10:08 pm
Hello,
is it possible to get new tweets without reloading the whole page? For example checking for new tweets every 15 minutes.
thanks
Brano
January 11th, 2010 at 11:25 pm
Hi Brano,
You should be able to do this fairly easily by creating an infinite loop with the setTimeout() method. You will need to create a function that runs the jQuery getScript() action and then add a setTimeout() (which calls your new function) to the end of the callback function.
Take a look at W3C Schools JavaScript Timing page if you get stuck.
Hope this helps,
Ian
January 12th, 2010 at 11:14 pm
What do I have to change to only display the tweet. So without the date and stuff..
Great script. Really helped me out! Thanks a lot!
January 12th, 2010 at 11:49 pm
Hi Phil,
All you would need to do is remove the code
<small>+relative_time(twitters[i].created_at)+</small>in thetwittercallback2function. This would then only display the latest tweet.I’m glad the script helped you out.
Thanks,
Ian
January 13th, 2010 at 12:19 am
Cheers Ian. Much appreciated
Thanks.
January 13th, 2010 at 8:32 am
No problem Phil!
April 9th, 2010 at 12:56 am
Hi Ian,
Somehow when I have fairly long tweets it does not show, is this a bug or am I doing something wrong?
Thanks
April 9th, 2010 at 3:24 pm
Hi Kerem,
Sorry to hear that you are having a problem, can you give me an example of the problem at all?
Thanks,
Ian
April 9th, 2010 at 7:48 pm
Thanks for the fast reply Ian.
So later on I sort of did a small debug session, its not the length of the tweets, basically it goes blank when I re-tweet.
Here, I downloaded your source code and only changed the username on the twitter.js file to my username and went to my twitter account and now my last tweet is a re-tweet.
Here’s the url http://keremsuer.com/twitter/
April 9th, 2010 at 4:26 pm
Hi, this is a great script, worked perfectly for me although i have annoying little boxes at either end of my tweet and i can t figure out what they are.. it displays as follows.. one little box before and one after. link: http://blitzmilkshakes.com/prototype/tweet.html
Latest Tweet..
�summer is almost here!� � less than a minute ago
April 12th, 2010 at 9:04 am
Hi Dean,
Thanks for the comments. This sounds like that your page is not using the UTF8 character set. Try putting in a meta tag like:
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />Let me know how you get on.
Thanks,
Ian
April 9th, 2010 at 11:24 pm
Alright so my latest thought is, it doesn’t display retweets made on Twitter.com.
But let’s say if you go to TechCrunch and retweet a story, it does display.
Let me know if you have trouble reproducing the bug.
April 12th, 2010 at 9:16 am
Hi Kerem,
I’ve had a look around and according the the Twitter API Wiki (http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline) the retweets are stripped out to preserve backwards compatibility:
“Note: For backwards compatibility reasons, retweets are stripped out of the user_timeline when calling in XML or JSON”
They suggest merging you user_timeline with your retweeted_by_me timeline. Take a look at http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-retweeted_by_me.
Or you could change the output to RSS (change the $.getScript url to include ‘ + usename + ‘.rss instead of ‘ + usename + ‘.json) and the parse the XML with jQuery.
Let me know how you get on. When I get a spare moment, I’ll take a look too.
Thanks,
Ian
May 7th, 2010 at 5:01 pm
Thanks for this wicked script!
May 7th, 2010 at 5:12 pm
Hi, Sorry. But this script seems to upset the other jquery stuff on my site?
Would it conflict with this?
All Jquery stops working.
Thanks
May 7th, 2010 at 5:19 pm
Ok SOrry to fill up your comments section
If I place the script tag at the bottom of my page, the other JQuery scripts work fine. But the twitter.js does not load.
http://www.huwsplace.co.uk/dev/
It just keeps on loading!
Could you please take a look and help me out?
Thanks
May 7th, 2010 at 6:48 pm
Hi Huw,
Thanks for you comments. I’ve sent you an email with the solution to your problem.
Just so you know, there will be a new version of this script on this blog in the next couple of days. Keep an eye out for that as it will fix a couple of issues that this script has.
Thanks again,
Ian
May 28th, 2010 at 9:25 am
All working great now thank you!
Very nice little script.
Cheers
May 31st, 2010 at 11:32 pm
Hi!
It’s working for me but not properly, it show a lot of tweets, and i only want the last tweet to be shown. Am i doing something wrong?
Thanks for the amazing script!
bernard
June 1st, 2010 at 12:33 pm
Hi Bernard,
Thanks for the comments!
Double check the end on the Twitter url. The end of the url should read
&count=1.That’s the bit that tells the Twitter API how many tweets to return.
Hope this helps.
Ian
Trackbacks & Pingbacks