Wednesday, April 15, 2009

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.

7 comments:

  1. Super useful, thanks!
    For me it didn't work until I changed:
    .append(data.results[url].shortUrl);
    To:
    .append(data.results[defaults.longUrl].shortUrl);

    ReplyDelete
  2. For more jQuery short url examples see http://to.ly/api_info.php

    ReplyDelete
  3. @Kannada sandalwood, thanks.

    @Anonymous Thanks for heads up. I will look into the code and see (on Monday morning). Thanks again...

    @Jonas Thanks for link.

    ReplyDelete
  4. This is really nice, but let me ask you, how can I detect the URL's in an input field (text are for example) and then shorten them on the fly using the above code?

    ReplyDelete
  5. @Tarek, You could bind an "on change" event to your input field and see check the string if it starts with "http://" (or https://) with javascript and if it is then use the above code to shorten it...

    ReplyDelete
  6. So good....
    Nice share. Allow me to try :)

    ReplyDelete
  7. Thanks a million.. It's 5AM and I have a project due for a client today. This is exactly one of the parts I need to keep moving forward at the pace I need.

    Thanks again!

    ReplyDelete