Make Your Own Web Site Badges with jQuery and JSON

Share this article

jquery-logo-sm

Services like Flickr, Delicious, and Twitter all offer JavaScript badges or widgets you can add to your site. But if you already use a JavaScript framework on your site, like jQuery, why would you want to add more JavaScript? Besides, it’s more fun to make your own. All of these services also offer a JSON format feed API, and rolling your own widget is easy. Here’s one I whipped up in no time for Twitter using jQuery. You’ll be surprised at how little code it requires.

All you need to use the Twitter JSON API is a URL:

http://twitter.com/status/user_timeline/sitepointdotcom.json?count=5&callback=yourfunction

Replace sitepointdotcom with any Twitter username, change the count=5 number to the number of tweets you wish to retrieve and yourfunction with the name of your callback function, and you’re ready to go. Copy that URL into the address field of your browser and you’ll be able to download the JSON data to have a look:

yourfunction([ ... ]);

The output is a call to your JavaScript function. An array that contains a collection of JSON objects — one for each tweet — is passed as the single argument. The idea is that you add a script element to your web page with the above URL as the source. This is necessary to bypass the Ajax security restriction present in most browsers where JavaScript is unable to make Ajax calls to domains other than the current one. It’s quite okay, however, to include a JavaScript source file from another domain; this is the standard way these sorts of badges work.

However, we’ll use another approach, because adding another script tag and making sure there’s a callback function sounds messy to me. We’re going to use the exceptionally handy getJSON function in jQuery. First though, we’ll need some HTML in which to put the widget data:

<div id="tweet">
  <p>
    <a href="http://twitter.com/sitepointdotcom">
        Follow me on Twitter
    </a>
  </p>
</div>

The idea is that all the Twitter updates are going to slot into that div element as separate paragraph elements. Nice and simple. I also like it because if the JavaScript fails to run for some reason, there’s meaningful content left on the page instead of, say, a loading animation that never finishes.

So I want this script to be fired off once the page is ready, and the best way to do that in jQuery is to use $(document).ready:

$(document).ready(function(){
  //our code goes here...
});

All the getJSON method needs is a URL. What’s good about this function is that if you add the query string parameter callback=? to the end of the URL, jQuery will take care of the callback function for you:

$(document).ready(function(){
  var tweeturl = "http://twitter.com/status/"
      +"user_timeline/sitepointdotcom.json?count=5"
      +"&callback=?";
  $.getJSON(tweeturl, function(data){
    //read the JSON data here...  
  });
});

jQuery will pass the JSON data to the function specified in the second argument as the data variable. We can then use each method to loop through all the tweets and insert them into our page’s HTML:

$.getJSON(tweeturl, function(data){
  $.each(data, function(i, item) {
    $('<p></p>')
        .addClass(i%2 ? 'even' : 'odd')
        .html(item.text)
        .prependTo('#tweet');
  });
});

If you go and check out the demo, you’ll see we now have a widget that pulls in Twitter data, converting each tweet to a HTML paragraph and inserting them into our page’s HTML. We also add a class value of odd or even to the tweets so that we can implement alternating background colors in CSS. So far so good, but what’s missing? Well I think any Twitter badge must at least link @replies, hashtags, and URLs; and adding some JavaScript regular expressions will do that job for us nicely:

var txt = item.text.replace(
  /(https?://[-a-z0-9._~:/?#@!$&'()*+,;=%]+)/ig,
  '<a href="$1">$1</a>'
).replace(
  /@+([_A-Za-z0-9-]+)/ig, 
  '<a href="http://twitter.com/$1">@$1</a>'
).replace(
  /#+([_A-Za-z0-9-]+)/ig,
  '<a href="http://search.twitter.com/search?q=$1">
      +'#$1</a>'
);
$('<p></p>')
  .addClass(i%2 ? 'even' : 'odd')
  .html(txt)
  .prependTo('#tweet');

That’s it! Go and have a look at the finished product. How simple was that?

The same approach can be taken with Delicious, Flickr, Last.fm, and even Yahoo Pipes. There’s plenty of room for improvement too; you could add time information, link to the tweet URL, add avatars, and so on. Raena, SitePoint’s other technical editor, suggested that you could even merge data from all those services together in reverse-chronological order to make a lifestream-style display. If you have a go at making your own, leave a comment and let me know.

Andrew TetlawAndrew Tetlaw
View Author

iOS Developer, sometimes web developer and Technical Editor.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week