Shorten long URLs with jQuery & bit.ly service

I recently signed up to twitter and actively engaging with people who are interested in jQuery. Twitter is a great service and there are all kinds of developers who are sharing interesting links and resources. So it is some kind of interest news group for me. Since you can only have 140 characters in your post, sharing long links limits you. URL shortening services to the rescue. There are lots of free URL shortening services, some are just for long URL shortening, some provide more features like real time click tracking, geostatistics and private URLs.

The great thing about them is that they also provide you with an API. So I thought that there is a way we can make a use of them in our jQuery code. One of the most popular services is bit.ly. You can read more about its API here.

I wrote a simple jQuery code that utilizes the service.

Here is an example:

(function($){
  // set up default options
  var defaults = {
    version:	'2.0.1',
    login:	'bitlyapidemo',
    apiKey:	'R_0da49e0a9118ff35f52f629d2d71bf07',
    history:	'0',
    longUrl:	''
  };

  // Build the URL to query
  var daurl = "http://api.bit.ly/shorten?"
    +"version="+defaults.version
    +"&longUrl="+defaults.longUrl
    +"&login="+defaults.login
    +"&apiKey="+defaults.apiKey
    +"&history="+defaults.history
    +"&format=json&callback=?";

    // Utilize the bit.ly API
    $.getJSON(daurl, function(data){

        // Make a good use of short URL
        $('#myContainer')
            .append(data.results[url].shortUrl);

    });
})(jQuery);

This code does not do much, but I hope you will find a good use of it in your own applications.