Adding your Twitter feed to your website with jQuery

PC-Pro-Twitter-page--462x346

Adding your Twitter feed to your website with jQuery

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.

Disclaimer: Some pages on this site may include an affiliate link. This does not effect our editorial in any way.

Todays Highlights
How to See Google Search History
how to download photos from google photos