Adding your Twitter feed to your website with jQuery

Image representing Twitter as depicted in Crun...

Image via CrunchBase

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:

// <![CDATA[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=?&#8221;, 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

  • 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,”$1“);
    }

    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(”

  • “” + urlToLink(tweet.text) + “”– ” + relTime(tweet.created_at) + “
  • “);

    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

    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.


    1. October 29, 2010 at 2:00 AM

      E-Commerce Website
      E-commerce web-site package is an ideal option for those starting their on-line business. AHMED ANMOL’S provides its customers with all up-to-date e-commerce features, required for a successful business on the Internet. This solution represents the perfect balance between a reasonable price and highly functional and easy-to-administrate system, aimed at expanding your business range and elevating your business to the next level.

      Solution Features:

      * Artistically developed advanced web design with custom graphics incorporated.
      * Professional logo design and flash header animation.
      * Flexibility. The amount of textual information, images and even pages and categories is unrestricted.
      * Content Management System. This is a very advanced and functional tool that enables the administrator to
      make all the required modifications to the site if needed in the course of time. It provides the site administrator with ability to add/delete/change all the types of textual data on the site, upload/add/delete/edit images and to perform the same operations with site pages and categories.
      * Mailing list / Newsletter engine
      * Shopping cart.
      * Online payment processing integration.
      * Order Tracking System. Enables a user to verify their orders’ status.
      * Members area developing.
      * Discount manager.
      * Advanced products search engine.
      * Shipping and Tax Counting
      * Multi browsers support

      The term of development – 2 weeks

    2. February 13, 2012 at 12:57 PM

      That is really interesting, You are an overly skilled blogger. I’ve joined your rss feed and stay up for seeking extra of your great post. Also, I have shared your web site in my social networks

    1. No trackbacks yet.

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    %d bloggers like this: