Placing your twitter feed on your site

An earlier post described the very involved process of including a Facebook status list to your website. Now let’s check out how to get a twitter feed onto your page, and I promise you, it is no where near as time consuming as the Facebook feed!

Due to twitter being available to the public from that start, twitter don’t need to have extensive security when it comes to reading and returning a users feed. Because of this, the process of displaying your tweets on your site is only a few lines of code!

Ok, so lets start by creating an element for the data to go into, something like:
<div id="twitter_feed"><h3>Tweets</h3></div>

Great, the hard part is done ;). Now to the twitter API and jQuery. JQuery’s getJSON function is perfect for this as twitter has the option to return the information needed in jSON format:
$.getJSON("http://twitter.com/statuses/user_timeline/ashrdurham.json?callback=?&count=3", function(data) {
$.each(data, function(i, object) {
$("#twitter_feed").append(object.text+"<br /><br />");
});
});

Complicated isn’t it? In the example above, the getJSON function is calling on twitter via URL and getting the data from a username, passing the variable count. For more details on this see the Twitter Developer Docs. Once the data is retrieved, we loop through each tweet and append it to the specified element. Simple right?

Now, I hear the questions, “What about links in the tweet? How can we make it so that they are actually links?”. Well I’m glad you asked. By adding the following function to the bottom of your javascript file:
function detect_link(text){
return text.replace(/(href="|)?[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function($0, $1) {
return $1 ? $0 : $0.link($0);
});
}

And modifying the twitter call slightly:
$.getJSON("http://twitter.com/statuses/user_timeline/ashrdurham.json?callback=?&count=3", function(data) {
$.each(data, function(i, object) {
$("#twitter_feed").append(detect_link(object.text)+"<br /><br />");
});
});

will turn any links in a post to clickable version of them.

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *