Advertisement
JavaScript & AJAX

Create a Fun Tweet Counter With jQuery

by

In this tutorial, we will look at using jQuery to call Twitter’s API and then use the results to create a widget for a blog or personal website that shows what hours during the day we tweet at the most.

The Twitter API is HTTP based, and can return results either as XML or JSON. As jQuery has a JSON
parser built-in, and tends to be lighter weight than XML, we’ll use that.

Sparklines

Since our widget will need to show the hourly usage visually, we’ll use a charting jQuery plugin called
Sparklines
to generate a graph of tweeting hours.

Final Product

When all is done, our widget should look like this.

Widget Final Preview

To make this happen, we’ll need to write some Javascript which performs the following:

  • Construct a URL to call the Twitter API
  • Parse the results as JSON
  • Enumerate through results, fetching the items we need
  • Use the items to create a set of data for the chart
  • Render the chart
  • Perform any final UI finishing touches

Lastly, once we have the code working, we’ll turn it into a jQuery plugin for
easy future use.

Step 1: Determining the Twitter API URL

Twitter API URL

There are quite a few extensive tutorials on the internet regarding jQuery and AJAX.
If you’re not familiar with AJAX however, the concept is simple. Javascript will open
up an HTTP connection and fetch the results of a URL. When the download is complete,
a function can be called (callback).

Before we can use AJAX, we need to construct the API URL that we’ll be calling.
Twitter has an extensive API which you can reference
(Twitter API Documentation),
but for this widget, we’ll only be performing a basic search.

The base URL for the search method is:

http://search.twitter.com/search.json

Query String Parameters

We can pass the parameters just like we would a regular JavaScript method, but we pass them
as query string values. The parameters we are interested in are:

  • "q" which is what we are searching for
  • "rpp" which lets us specify how many results we’d like
    returned (for this widget we'll do 50).

Also, since we’re going to be using AJAX to download
data from another domain (twitter.com), we’ll need to use JSONP which allows us to forgo the security
concerns within the browser. JQuery automatically will handle this for us, we just need to
attach "callback=(function name)" to our URL. Since we’ll be using an anonymous function,
this value will be "?".

Our final URL for the Twitter API

http://search.twitter.com/search.json?callback=?&rpp=50?q=from:{twittername}

Step 2: Executing the API Call

JSON result in FireBug

$.getJSON()

Now that we know where we’re going to make the call, we can write some Javascript to actually
perform it. JQuery includes a method that will handle the entire AJAX call for us,
and parse the JSON results, returning objects. That method is $.getJSON(). It takes two parameters, one for the URL,
and one for the callback function.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    
    $(function() {
        var twitterName = 'nettuts';
        $.getJSON(
            'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName,
            function(data) {
                // our code to handle the data here
            }
        );
    });
    
</script>

Step 3: Enumertaing Results

The results coming back from Twitter resemble the following structure.

jsonp1241596748896 (
	{
	"results":
		[
			{
                "text":""Monday Madness" at papajohn's -- $6 pizza",
                "to_user_id":null,
                "from_user":"andstuff","
                id":1703714190,
                "from_user_id":85548,
                "iso_language_code":"en",
                "source":"<a href="http:\/\/funkatron
                .com\/spaz">Spaz<\/a>",
                "profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production
                \/profile_images\/52440056\/lttwitter_normal.jpg",
                "created_at":"Tue, 05 May 2009 05:43:39 +0000"
            },
            ... 
            (more tweet objects here)
        ],
    "since_id":0,
    "max_id":1714318174,
    "refresh_url":"?since_id=1714318174&q=from%3Aandstuff",
    "results_per_page":50,
    "total":9,
    "completed_in":0.100973,
    "page":1,
    "query":"from%3Aandstuff"
    }
);

Notice that the objects which contain the data we want are child objects of a child object.
For our widget we’ll attempt to find the "results" collection object by looking for two
things: the item which has a length (it’s an array) and the item which has children
items that have the property "created_at". Once we find
this parent item, we can loop through it to assemble our data.

    $(function() {
        var twitterName = 'nettuts';
        $.getJSON(
            'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName,
            function(data) {
                $.each(data, function(i, tweets) {
                    if (tweets.length != undefined)
                        if (tweets[0].created_at != undefined)
                            // tweets[] is an array of all the tweet items
                    };
                })
            }
        );
    });

Step 4: Building Our Data Set to Display

Widget Final Preview

Recall that we will be creating a widget that shows a chart of our hourly tweets.
In order to create the chart, we’ll need to assemble that data in an array. We can do this by
turning the "created_at" property into a Date() object then extracting the hour (0-24).
We’ll keep an array called "usageData" which we will increment to keep track of how many tweets per hour.
We’ll use a for loop to go through each item, and simply add to the usageData array
when that hour is found.

    $(function() {
        var twitterName = 'nettuts';
        var usageData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $.getJSON(
            'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName,
            function(data) {
                $.each(data, function(i, tweets) {
                    if (tweets.length != undefined)
                        if (tweets[0].created_at != undefined)
                        for (i = 0; i < tweets.length; i++) {
                            var usageHour = (new Date(tweets[i].created_at)).getHours();
                            usageData[usageHour]+=2;
                        };
                })
            }
        );
    });

This should fill usageData with values like...

[0, 0, 6, 8, 10, 6, 4, 12, 12, 10, 8, 0, 2, 4, 2, 0, 8, 10, 0, 0, 4, 2, 0, 0]

Step 5: Rendering the UI

If you haven’t yet downloaded Sparklines plugin, go ahead and do that now, and then drop
the script file reference on to your page.

<script type="text/javascript" src="jquery.sparkline.min.js"></script>

Before we call the chart code, we need to create a container tag for it to exist in. Somewhere
on your page, add a div with class “twitterUsage”. We’ll access this from jQuery in the code to
create our chart.

<div class="twitterUsage"></div>

Sparklines is very simple to use. We simply need to call the sparkline() method off of any
jQuery wrapped set to create a new chart inside of that element. After we’ve created our chart,
we’ll add a short summary line describing what the chart data represents (tweets per hour).

Our whole head section should now look like this.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.sparkline.min.js"></script>
<script type="text/javascript">

    $(function() {
        var twitterName = 'nettuts';
        var usageData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $.getJSON(
            'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName,
            function(data) {
                $.each(data, function(i, tweets) {
                    if (tweets.length != undefined)
                        if (tweets[0].created_at != undefined)
                        for (i = 0; i < tweets.length; i++) {
                            var usageHour = (new Date(tweets[i].created_at)).getHours();
                            usageData[usageHour] += 2;
                        };
                })

                $(".twitterUsage").sparkline(usageData, { type: 'bar' });
                $('<span>' + twitterName + ': tweets per hour</span>').insertAfter($(".twitterUsage canvas"));
            }
        );
    });
</script>

Run the code, and you should get something that resembles the following.

Step 6: Adding Design

For this widget, I’d like to see the chart overlaying the Twitter logo,
so I’ll set that as the background-image on the div. I’ll also throw a bit of
font and color styling on the description text as well. (Note: The twitter logo
background file is available in the source files. It is 120px wide if you prefer
to create it yourself.)

    .twitterUsage  
    {
        width: 120px; 
        height: 40px; 
        padding-top: 15px; 
        background: transparent url('twitter-logo-bg.gif') no-repeat top center; 
    }
        
    .twitterUsage span 
    { 
        display: block; 
        color: #0482AD; 
        font-size: 9px; 
        text-align: center; 
        font-family: Sans-Serif; 
    }

Lastly, we can adjust the sparklines() method to include some styling options:

    $(".twitterUsage").sparkline(usageData,
        {
            type: 'bar',
            barColor: '#4D4D4D',    // Dark gray
            height: 25
        });

Step 7. Converting Our Widget to a Plugin

The last thing we need to do is convert our working widget into a plugin.
Because our widget is not too complex, this will be as simple as copying our code
to an external file, defining $ as jQuery, and adding our code an extension method
to the jQuery object. (Note also the slight change to .insertAfter)

Create a new javascript file called "jquery.twittergraph.js".
Paste the following into the file (or type out the changes yourself if you prefer).

(function($) {
    $.twitterGraph = function(twitterName, element) {
        var usageData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        $.getJSON(
                'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName,
                function(data) {
                    $.each(data, function(i, tweets) {
                        if (tweets.length != undefined)
                            if (tweets[0].created_at != undefined)
                            for (i = 0; i < tweets.length; i++) {
                                var usageHour = (new Date(tweets[i].created_at)).getHours();
                                usageData[usageHour] += 2;
                        };
                    })

                    element.sparkline(usageData,
                        {
                            type: 'bar',
                            barColor: '#4D4D4D',
                            height: 25
                        });

                    $('<span>' + twitterName + ': tweets per hour</span>').insertAfter(element.find("canvas"));
                }
            );
    };
})(jQuery);

We can now call our widget with:

$.twitterGraph('nettuts', $(".twitterUsage"));

The complete code for our HTML page is as follows.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>TwitterGraph</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.sparkline.min.js"></script>
        <script type="text/javascript" src="jquery.twittergraph.js"></script>
        <script type="text/javascript">
            $(function() {
                $.twitterGraph('nettuts', $(".twitterUsage"));
            });
        </script>
        
        <style type="text/css">
            .twitterUsage { width: 120px; height: 40px; padding-top: 15px; background: transparent url('twitter-logo-bg.gif') no-repeat top center; }
            .twitterUsage span { display: block; color: #0482AD; font-size: 9px; text-align: center; font-family: Sans-Serif; }
        </style>
        
    </head>
    <body>

        <div class="twitterUsage"></div>
        
    </body>
    </html>
Widget Final Preview


Related Posts
  • Web Design
    HTML & CSS
    Easier Visual Data in the Browser With Variance ChartsVariance thumb
    Today, we will be diving into Variance Charts; a unique JavaScript based "grammer of graphics" which provides an abstract, declarative markup style to create what would otherwise be fairly complex charts. Read More…
  • Web Design
    HTML & CSS
    Build a Dynamic Grid with Salvattore and Bootstrap in 10 MinutesSalvatorre thumb
    Today, we will use Salvattore in combination with Twitter Bootstrap 3 to make a responsively awesome flowing grid structure.Read More…
  • Code
    JavaScript & AJAX
    Connect 4 With Socket.ioSocket io wide retina preview
    Today we'll see how we can use Node.js and Socket.io to create a multiplayer Connect 4 style game.Read More…
  • Code
    JavaScript & AJAX
    Ember Components: A Deep DiveEmber components retina preview
    Ember.js is a JavaScript MVC framework that allows developers to create ambitious web applications. Although pure MVC allows a developer to separate concerns, it does not provide you with all the tools and your application will need other constructs. Today, I'm going to talk about one of those constructs. Ember components are essentially sandboxed re-usable chunks of UI. If you are not familiar with Ember, please check out Getting Started With Ember.js or the Let's Learn Ember Course. In this tutorial, we will cover the Web Components specification, learn how to write a component in Ember, talk about composition, explain the difference between an Ember view and an Ember component, and practice integrating plugins with Ember components.Read More…
  • Code
    JavaScript & AJAX
    Getting Into Ember.js: Part 5Getting into ember
    Editor's Note: The Ember.js team has shifted to an expedited release schedule and as of this publication date are on version 1.2.0. This tutorial was written pre-v1.0 but many of the concepts are still applicable. We do our best to commission timely content and these situations happen from time-to-time. We'll work to update this in the future. In part 3 of my Ember series, I showed you how you can interact with data using Ember's Ember.Object main base class to create objects that define the methods and properties that act as a wrapper for your data. Here's an example:Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…