Create a Fun Tweet Counter With jQuery
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.

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



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:
1 |
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
1 |
http://search.twitter.com/search.json?callback=?&rpp=50?q=from:{twittername}
|
Step 2: Executing the API Call



$.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.
1 |
|
2 |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> |
3 |
<script type="text/javascript"> |
4 |
|
5 |
$(function() { |
6 |
var twitterName = 'nettuts'; |
7 |
$.getJSON( |
8 |
'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName, |
9 |
function(data) { |
10 |
// our code to handle the data here
|
11 |
}
|
12 |
);
|
13 |
});
|
14 |
|
15 |
</script> |
Step 3: Enumertaing Results
The results coming back from Twitter resemble the following structure.
1 |
|
2 |
jsonp1241596748896 ( |
3 |
{ |
4 |
"results": |
5 |
[ |
6 |
{ |
7 |
"text":""Monday Madness" at papajohn's -- $6 pizza", |
8 |
"to_user_id":null, |
9 |
"from_user":"andstuff"," |
10 |
id":1703714190, |
11 |
"from_user_id":85548, |
12 |
"iso_language_code":"en", |
13 |
"source":"<a href="http:\/\/funkatron |
14 |
.com\/spaz">Spaz<\/a>", |
15 |
"profile_image_url":"http:\/\/s3.amazonaws.com\/twitter_production |
16 |
\/profile_images\/52440056\/lttwitter_normal.jpg", |
17 |
"created_at":"Tue, 05 May 2009 05:43:39 +0000" |
18 |
}, |
19 |
... |
20 |
(more tweet objects here) |
21 |
], |
22 |
"since_id":0, |
23 |
"max_id":1714318174, |
24 |
"refresh_url":"?since_id=1714318174&q=from%3Aandstuff",
|
25 |
"results_per_page":50, |
26 |
"total":9, |
27 |
"completed_in":0.100973, |
28 |
"page":1, |
29 |
"query":"from%3Aandstuff" |
30 |
} |
31 |
); |
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.
1 |
|
2 |
$(function() { |
3 |
var twitterName = 'nettuts'; |
4 |
$.getJSON( |
5 |
'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName, |
6 |
function(data) { |
7 |
$.each(data, function(i, tweets) { |
8 |
if (tweets.length != undefined) |
9 |
if (tweets[0].created_at != undefined) |
10 |
// tweets[] is an array of all the tweet items
|
11 |
};
|
12 |
})
|
13 |
}
|
14 |
);
|
15 |
});
|
Step 4: Building Our Data Set to Display

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.
1 |
|
2 |
$(function() { |
3 |
var twitterName = 'nettuts'; |
4 |
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]; |
5 |
$.getJSON( |
6 |
'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName, |
7 |
function(data) { |
8 |
$.each(data, function(i, tweets) { |
9 |
if (tweets.length != undefined) |
10 |
if (tweets[0].created_at != undefined) |
11 |
for (i = 0; i < tweets.length; i++) { |
12 |
var usageHour = (new Date(tweets[i].created_at)).getHours(); |
13 |
usageData[usageHour]+=2; |
14 |
};
|
15 |
})
|
16 |
}
|
17 |
);
|
18 |
});
|
This should fill usageData with values like...
1 |
[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.
1 |
<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.
1 |
<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.
1 |
|
2 |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> |
3 |
<script type="text/javascript" src="jquery.sparkline.min.js"></script> |
4 |
<script type="text/javascript"> |
5 |
|
6 |
$(function() { |
7 |
var twitterName = 'nettuts'; |
8 |
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]; |
9 |
$.getJSON( |
10 |
'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName, |
11 |
function(data) { |
12 |
$.each(data, function(i, tweets) { |
13 |
if (tweets.length != undefined) |
14 |
if (tweets[0].created_at != undefined) |
15 |
for (i = 0; i < tweets.length; i++) { |
16 |
var usageHour = (new Date(tweets[i].created_at)).getHours(); |
17 |
usageData[usageHour] += 2; |
18 |
};
|
19 |
})
|
20 |
|
21 |
$(".twitterUsage").sparkline(usageData, { type: 'bar' }); |
22 |
$('<span>' + twitterName + ': tweets per hour</span>').insertAfter($(".twitterUsage canvas")); |
23 |
}
|
24 |
);
|
25 |
});
|
26 |
</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.)
1 |
|
2 |
.twitterUsage |
3 |
{ |
4 |
width: 120px; |
5 |
height: 40px; |
6 |
padding-top: 15px; |
7 |
background: transparent url('twitter-logo-bg.gif') no-repeat top center; |
8 |
} |
9 |
|
10 |
.twitterUsage span |
11 |
{ |
12 |
display: block; |
13 |
color: #0482AD; |
14 |
font-size: 9px; |
15 |
text-align: center; |
16 |
font-family: Sans-Serif; |
17 |
} |
Lastly, we can adjust the sparklines() method to include some styling options:
1 |
|
2 |
$(".twitterUsage").sparkline(usageData, |
3 |
{
|
4 |
type: 'bar', |
5 |
barColor: '#4D4D4D', // Dark gray |
6 |
height: 25 |
7 |
});
|



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).
1 |
|
2 |
(function($) { |
3 |
$.twitterGraph = function(twitterName, element) { |
4 |
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]; |
5 |
$.getJSON( |
6 |
'http://search.twitter.com/search.json?callback=?&rpp=50&q=from:' + twitterName, |
7 |
function(data) { |
8 |
$.each(data, function(i, tweets) { |
9 |
if (tweets.length != undefined) |
10 |
if (tweets[0].created_at != undefined) |
11 |
for (i = 0; i < tweets.length; i++) { |
12 |
var usageHour = (new Date(tweets[i].created_at)).getHours(); |
13 |
usageData[usageHour] += 2; |
14 |
};
|
15 |
})
|
16 |
|
17 |
element.sparkline(usageData, |
18 |
{
|
19 |
type: 'bar', |
20 |
barColor: '#4D4D4D', |
21 |
height: 25 |
22 |
});
|
23 |
|
24 |
$('<span>' + twitterName + ': tweets per hour</span>').insertAfter(element.find("canvas")); |
25 |
}
|
26 |
);
|
27 |
};
|
28 |
})(jQuery); |
We can now call our widget with:
1 |
$.twitterGraph('nettuts', $(".twitterUsage")); |
The complete code for our HTML page is as follows.
1 |
|
2 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
3 |
|
4 |
<html xmlns="http://www.w3.org/1999/xhtml"> |
5 |
<head>
|
6 |
<title>TwitterGraph</title> |
7 |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> |
8 |
<script type="text/javascript" src="jquery.sparkline.min.js"></script> |
9 |
<script type="text/javascript" src="jquery.twittergraph.js"></script> |
10 |
<script type="text/javascript"> |
11 |
$(function() { |
12 |
$.twitterGraph('nettuts', $(".twitterUsage")); |
13 |
});
|
14 |
</script>
|
15 |
|
16 |
<style type="text/css"> |
17 |
.twitterUsage { width: 120px; height: 40px; padding-top: 15px; background: transparent url('twitter-logo-bg.gif') no-repeat top center; } |
18 |
.twitterUsage span { display: block; color: #0482AD; font-size: 9px; text-align: center; font-family: Sans-Serif; } |
19 |
</style>
|
20 |
|
21 |
</head>
|
22 |
<body>
|
23 |
|
24 |
<div class="twitterUsage"></div> |
25 |
|
26 |
</body>
|
27 |
</html>
|

- Follow us on Twitter, or subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.