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:
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

$.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

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>

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



first one
That shite is annoying. Auto-ban/delete needs to be instituted for these “First!” posts. Like what Lifehacker did.
agreed, a regular expression could be used
firsters make me rage.
I think I might just kill you
When you were a sperm, you could say “first”.
but,
if you’re nominated for Darwin’s Awards, you do not say “first”.
If you find a girlfriend and you …, you do not say “first”.
if you raised one foot on the moon, you do not say “first”.
One thing is sure, you do not and never will be the first to say “first” on a forum.
you are like the H in Hawaii … you’re useless.
otherwise, surely, it’s a nice and instructive tutorial.
thanks a lot.
Neat, thanks.
Seems pretty sweet. A little complicated, but worth the brain power! Thanks!
Looks great and easy, thanks :)
Cool! I think that will have onto onw of my many wesbites….
Thanks Titus!
Nice Article! Thanks! :)
Fun tutorial Titus!
agree!! this is a fun tutorial :D
Nice tutorial.
nice one!
Thanks! Might use this one!
This is an amazing piece, it will definitely come in very handy.
Thanks for sharing :)
Very cool idea; and a great introduction to using a RESTful service API!
Fun little tutorial :)
Thanks for posting.
Looks pretty nice! Why not add a demo to this page, would like to see it in action without having to download it.
Can’t wait to see more of these interesting articles :) . Keep it up
This is great! Thanks.
There’s no demo page because this script won’t work for more than one hour on a website like netttuts+ : http://apiwiki.twitter.com/Rate-limiting
Very nice tutorial – functional, yet fun; not to easy but not to hard either. This fits in great with the twiiter craze and plugin development.
Of course my perplexing bug I couldn’t figure out was using ‘twitterUsage’ as an id in my div, but calling it as a class in my script. Arg.
Another error I couldn’t figure out as a undefined error from the conditional statement – if(tweets[0] != undefined). Firefox was stopping at that point and throwing an error. When I copied and pasted the code for the plugin script instead of rewriting everything though, the error went away, even though nothing I could see has changed around that error.
Navigating the JSON results is an area of code that could be improved. For the area you’re talking about, there are two conditional statements that are used. However, the code you included in your post is neither of them….
if (tweets.length != undefined) // <<– is this the one you meant?
if (tweets[0].created_at != undefined)
The first just identifies if the current item is an array, the second checks to make sure it’s an array containing the items we want.
I haven’t tested this, so your mileage may vary, but perhaps this would be an easier-to-read version of the same code:
if (tweets.constructor == “Array”)
if (tweets[0].created_at != undefined)
Oh, and the id/class issue… I do that too sometimes! It’s one of those mistakes that’s up there with forgetting the ; at the end of the line.
Do we need it?
Great tut, thanks for sharing :)
Seems nice!
nice tutorial
I soooo didn’t understand the usageData -part, but ohwell xD
Seems very usefull though.
Maybe I can help. Working backwards, a graph is really just a visual representation of a number. So we’re going to have a graph that’s has 24 values, one for each hour in the day. The easiest way to store that is in an array.
With that array, the index will match the hour of the day. So noon would be usageData[12]. Midnight would be usageData[0]. And so on.
When the code enumerates the tweets[] array, it looks at what hour the tweet was posted (var usageHour). It increments that value.
Hope that made it clearer.
At first I didn’t understand by reading what you wrote.
But now when I reviewed the code again, and had your comment in my head, I now understand!
So it gets the hour that the tweet was made(say for example 21), and then it adds 2 to that value in the array, and if then later another tweet was made during that hour, the value of usageData[21] would be increased by 2 again, so it’d be a value of 4.
Is this correct? Thanks btw
@Tanax:
Yup — you got it exactly.
thanks for the tutorial…would love to see a demo page though!
Cool tutorial. I Enjoyed it!
Incidentally I also posted a tutorial today related to Twitter’s search API on my blog! You worked on the JSON format and I worked on the Atom format.
http://iambari.com/2009/05/19/parse-twitter-search-atom-feed-using-php-and-jquery/
Nice tutorial thanks
Thanks for the tutorial!
Okay, this was one of the best tutorials, ever published on Nettuts! Thanks for it!
Nice article, i ve been reading this article from the beginning slowly, by now im getting clear, thanks
At least you guys did it so I don’t have to. Seems pretty complicated but could Look pretty cool on any portfolio site.
Man, it’s a genius thing! Awesome!
WOW! This tutorial really helped me out with a little project I had to work on today. You just saved me a lot of research and made me look like a rock star at the same time. Thanks a ton!
nice!!!! thanks
Definitely a sweet little script. jQuery to the rescue again.
Hey thanks, looking forward to some more Twitter API tuts..
awesome! though i wont be using it…
cool one .. ! looking forward for more tuts on twitter like this …
Just the type of article i love…..not too complex yet immensly usefull.
I realize this tutorial was from months ago, but I finally decided to give it a run. I’m new to Javascript, so forgive me if this may seem like a stupid question: how do you change the width of the bars? I figured out how to change the height, as it’s in “STEP #7″, but when I add a comma after the “height” attribute, and add “width: 10″ on the next line, it doesn’t affect anything at all. Am I missing something here?
Nevermind, I figured it out. I opened up the sparkline.js file, and searched for “bar” (the type of graph), and found the spacing and width parameters in there.
http://www.aon-media.com/slapping_range
Thanks for the great tut!
Nice, I’ve been meaning to check out the twitter api, this is a nice introduction.
There is so much awesomeness in this tutorial I can’t begin to find enough praise. I never knew you could do such complex operations with just data and jQuery – I had before been using php to render the graphs.
Very cool little widget, but why do you increment by =+2 when looping through the Tweets for each hour? Wouldn’t it be =+1?