Make Your Own Web Site Badges with jQuery and JSON

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.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Phil

    What would be the best way of filtering out @ replies from this example? Not doing doesn’t really make sense outside the context of Twitter, if you’re not following the user being replied to.

  • Buck 50 Prod

    Very helpful app!!

  • redundant

    If you are wondering why their are no comments to this post, the link in the email goes too 4/20 not 4/21. You might want to redirect the 4/20 to 4/21.

    Regards,
    Richard

  • http://www.magain.com/ mattymcg

    @redundant Thanks, this has been fixed. Sorry for the mishap all.

  • Anonymous

    What would be the best way of filtering out @user replies in the Twitter example? They don’t seem relevant out of the context of Twitter itself, where you’d only see replies for users you’re following.

  • Mark

    But using javascript to make a badge is worse for SEO right?

  • chrisdillon

    Brilliant! Thanks for the inspiration.
    I added my recent Delicious to my About page at http://chrisdillon.us/about.
    Here’s code for Delicious:

    /*
    object example:
    {"u":"http://www.businesspundit.com/coworking-vs-the-coffee-shop-who-wins/",
    "d":"Coworking vs. the Coffee Shop: Who Wins? | Business Pundit",
    "t":["coworking"],
    "dt":"2009-04-22T13:33:06Z",
    "n":"",
    "a":"chrisdillon.us"}
    */

    $(function() {
    $.getJSON("http://feeds.delicious.com/v2/json/chrisdillon.us?count=5&callback=?",
    function(data){
    $.each(data, function(i, item){
    var txt = "<a href="' + item.u + '">' + item.d + '</a>';
    // add tags
    txt += ' |';
    $.each(item.t, function(j, tag){
    txt += ' <a class="delicious-tag" href="http://delicious.com/' + item.a + '/' + tag + '">' + tag + '</a>';
    });
    // add to container
    $('<p></p>').addClass(i%2 ? 'even' : 'odd').html(txt).appendTo('#delicious-container');
    });
    });
    });

    Cheers,
    Chris Dillon

  • Hans

    Nice. One thing though. I would like to sort the tweets top-down, the newest on top of the badge and so on. How can I accomplish that?

  • http://e-make-money-online.com Adsensing

    This is really a helpful app. Hope I’ll use this app in my existing sites. Thanks for sharing!!!

  • ossreleasefeed

    Is this supposed to work when run from localhost? I tried out the code exactly as in the example but get nothing back.

    Thx,
    Schalk

  • timboreader

    @ossreleasefeed – make sure you’re using the latest verion of jquery. I wasn’t and it didn’t work for me either for a few goes.

    @Hans – agreed! – Anyone got an answer for this? I’ve looked in the api documentation and there are no parameters for ordering the tweets. I would love to apply this script to some live sites of mine, but (IMO) it isn’t any use if it can’t go in reverse chronological order.

    Ta

  • surfbuds.net

    To have it in reverse order from the example just use appendTo instead of prependTo and use Javascript to add the Title “follow me on twitter” at the end of the loop..

    I’ve made it work for a real RSS feed translated via PHP to JSON, which has a bit more complex structure.. anyone who wants the code let me know from my inquiry form at http://www.surfbuds.net/eng/profile/jm