Skip to navigation

PCPro-Computing in the Real World Printed from www.pcpro.co.uk

Register to receive our regular email newsletter at http://www.pcpro.co.uk/registration.

The newsletter contains links to our latest PC news, product reviews, features and how-to guides, plus special offers and competitions.

// Home / Blogs

Posted on September 13th, 2010 by Ian Devlin

Adding your Twitter feed to your website with jQuery

PC Pro Twitter page

If you or your company has a Twitter account, chances are you’d like to promote it and display your latest tweets from your website. Since many websites – both personal and increasingly business – are built on blogging software such as WordPress, this is usually achieved via a plugin, of which there are many out there.

But what if you simply want to add your live Twitter feed to a “normal” web page? Twitter itself provides a number of HTML widgets, but in this article I’ll show you how easy it is to achieve with a little bit of JavaScript, CSS, and jQuery.

In case you haven’t come across it before:

What is jQuery?

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. It’s very powerful and makes life a whole lot easier when writing JavaScript. To include jQuery in your webpage, simply add the following within the <head> tags:

<script type="text/javascript" src="http://jqueryjs.google
code.com/files/jquery-1.3.2.min.js"></script>

This uses the version that is hosted on Google Code, which saves you having to download the file.

Twitter API

Twitter itself provides a complicated API to allow access to all sorts of things. A lot of this complication arises around authentication, and necessarily so, but thankfully to simply retrieve a stream of tweets, authentication isn’t required (as long as the user in question hasn’t hidden their tweets).

First of all the API provides many different ways to obtain a user’s statuses. I won’t go into any of them other than the one that I favour, and this is the one that I’ll talk about here: user_timeline.

user_timeline

This returns a number of the most recent statuses posted by the user. It can return the data in different formats: XML, JSON, RSS and Atom. I favour  JSON, a lightweight data-interchange format, so this is the one that I will talk about.

You can use a number of parameters, and a full list of what they can do can be found on the Twitter API description for user_timeline. For now, I will only use a few relevant ones.

Give me the Tweets!

To retrieve the data for a particular Twitter account (I will use pcpro in this example here) you call the following:

$.getJSON("http://twitter.com/statuses/user_timeline.json?
screen_name=pc_pro&count=10&callback=?",
function(tweetdata) {
// do some stuff here
});

This will return the last 10 tweets from the pc_pro account in JSON format in the tweetdata variable. By default, retweeted tweets are not included in this feed, but to include them, add the &include_rts=1 parameter above, and they will be returned.

Of course we now have to make sense of this data, parse it and actually do something with it.

On our HTML page, define a <ul> and give it the id tweet-list. This is where we will hold our tweets. The above code is then extended to do the following:

$.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=pc_pro&count=1O&callback=?", function(tweetdata) {
var tl = $("#tweet-list");
$.each(tweetdata, function(i,tweet) {
tl.append("<li>“" + tweet.text + "”– " + tweet.created_at + "</li>");
});
});

Some explanations: var tl = $("#tweet-list"); grabs a reference to the <ul> element that we created above. We need this as we will add each tweet to it.

$.each(tweetdata, function(i,tweet) {... is the start of a jQuery loop, in this case iterating through each item in tweetdata and storing it temporarily in tweet. The following line then adds the tweet within an <li> item. The actual text of the tweet is contained within the text data member, and here we put double quotes around it, and the time it was created is contained within the created_at data member.

This will now display the last 10 tweets in list format on the relevant HTML page.

However, if there are links contained in the tweet, they won’t be clickable, and the created date is a bit long and not like the Twitter standard timelines such as “about a minute ago” or “two hours ago”. We can fix this with the following two functions urlToLink(); which we call on tweet.text:

function urlToLink(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}

and relTime(); which we call on tweet.created_at:

function relTime(time_value) {
time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,"");
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
if (timeago < 60) return 'less than a minute ago';
else if(timeago < 120) return 'about a minute ago';
else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
else if(timeago < (90*60)) return 'about an hour ago';
else if(timeago < (24*60*60)) return 'about ' + (parseInt(timeago / 3600)).toString() + ' hours ago';
else if(timeago < (48*60*60)) return '1 day ago';
else return (parseInt(timeago / 86400)).toString() + ' days ago';
}

So we need to change the above line to the following:

tl.append("<li>“" + urlToLink(tweet.text) + "”– " + relTime(tweet.created_at) + "</li>");

This will be called when the HTML page is loaded (or you can load it some other time, it’s up to you of course) and this is done using jQuery by inserting the code within:

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

which basically calls the code when the entire DOM has been loaded.

End Result

I have put together an example using all the code above, so you can see all this together and working for yourself. Plus you can view the code to see how it’s done. It’s all commented too, probably overly so, in case you get stuck.

You can of course also style the list and its contents with CSS, but I’ll leave that as an exercise for the reader.

*Update*

One of the comments below asked about retrieving the latest statuses from a specific account’s list. I’ve created a quick example that retrieves and displays the latest updates from PC Pro’s ’staff’ Twitter list. You can of course view the source code.

The main difference is the URL in included in the &.getJSON() call which should be:

http://api.twitter.com/1/account-name/lists/list-name/statuses.json?callback=?

where account-name is the name of the account, in this case pc_pro, and list-name is the name of the list, in this case staff.

Tags: , ,

Posted in: How To

Permalink

Follow any responses to this entry through the RSS 2.0 feed.

You can skip to the end and leave a response. Pinging is currently not allowed.

14 Responses to “ Adding your Twitter feed to your website with jQuery ”

  1. John McLean Says:
    September 13th, 2010 at 1:50 pm

    Looks like something has gone funky with your script (or maybe the format of the dates returned by Twitter) – they all say “NaN days ago”.

    On further investigation, looks like Date.parse (at least on IE8) doesn’t like the “+0000″ in the date returned by Twitter. This can be corrected by adding the following two lines to the start of the relTime() function:

    var exp = /(\+[0-9]{4}\s)/ig;
    time_value = time_value.replace(exp,”");

     
  2. Ian Devlin Says:
    September 13th, 2010 at 2:14 pm

    Hi John, thanks for point that out. I have updated the article and also the examples provided.

     
  3. lissnup Says:
    September 13th, 2010 at 3:57 pm

    This works like a charm, thanks! But when I tried to apply the same methods/logic to retrieve the status updates of a list [see http://dev.twitter.com/doc/get/:user/lists/:id/statuses I drew a blank. If anyone has any clues why that is I would be SO grateful.

     
  4. Ian Devlin Says:
    September 13th, 2010 at 4:22 pm

    Hi lissnup, I’ve put together an example of retrieving the statuses from the pcpro staff list who’s code you can view.

    Pay particular attention to the Twitter URL that is called.

     
  5. lissnup Says:
    September 13th, 2010 at 4:36 pm

    Ian, you are my hero! Thank you so much.

     
  6. Ian Devlin Says:
    September 15th, 2010 at 9:30 am

    I’ve updated all the examples to reflect the change in PC Pro’s Twitter account from pc_pro to pcpro!

     
  7. Alastair Says:
    September 15th, 2010 at 10:57 am

    Hi Ian
    Though you’ve updated the examples, you’ve still got a link to the @pc_pro account in the paragraph under “Give me the Tweets!”
    Great article however…

     
  8. Ian Devlin Says:
    September 15th, 2010 at 11:01 am

    Thanks Alastair, that’s now fixed. Of course the image is also now wrong, but I think we can live with that.

     
  9. Stephen Bennett Says:
    September 19th, 2010 at 4:56 pm

    I only skim-read this article, but isn’t this functionality already available via Twitter’s own widgets? http://twitter.com/goodies/widget_profile

     
  10. Ian Devlin Says:
    September 20th, 2010 at 8:41 am

    Yes Stephen, it is, but you have limited control over how it looks. This way you can make them appear as you like and simply style them in CSS.

     
  11. Homero Says:
    November 1st, 2010 at 4:16 pm

    What about the new, OAuth-based method? The sites with this code are getting splashed with a dialog box for password and login.
    How fix this?
    Tanks.
    Homero

     
  12. mark Says:
    November 5th, 2010 at 8:10 am

    the date is saying about 7 hours ago when the tweet was added only a few minutes ago – is there a default GMT setting? I’m in asia 7 hours ahead of GMT

     
  13. J Wilson Says:
    October 24th, 2012 at 11:20 pm

    Why would this suddenly stop working in October 2012 ? It was working find in September ?

     
  14. Ian Devlin Says:
    October 25th, 2012 at 8:21 am

    Twitter have changed their API so the URL in the $.getJSON() call is no longer correct.

    It should now be something like:
    http://api.twitter.com/1/statuses/user_timeline.json?screen_name=pc_pro&count=1O&callback=?

    Thanks to J. Wilson for bringing this to my attention.

     

Leave a Reply

Spam Protection by WP-SpamFree

* required fields

* Will not be published

Authors

Categories

Archives

advertisement

SEARCH
SIGN UP

Your email:

Your password:

remember me

advertisement


Hitwise Top 10 Website 2010