longURL

by tcloninger

HTML

<a href="http://bit.ly/d29A5B">Here's a link.</a>
<a href="http://bit.ly/d29A5B">Here's a link.</a>

JavaScript

(function($){
   
  // Store fetched long URLs here.
  var cache = {};
   
  $.longUrl = function( url, callback ) {
    var api = "http://www.longurlplease.com/api/v1.1?callback=?";
     
    if ( cache[ url ] ) {
      // URL exists in cache, so use it.
      callback( cache[ url ] );
       
    } else {
      // Fetch JSON data.
      $.getJSON( api, { q: url }, function(data){
        if ( data[ url ] ) {
          // If the data is valid, update the cache.
          cache[ url ] = data[ url ];
           
          // Call `callback` for this element + long url.
          callback( cache[ url ] );
        }
      });
    }
  }
   
  $.fn.longUrl = function( options ) {
    // Override defaults with specified options.
    options = $.extend( {}, $.fn.longUrl.options, options );
     
    return this.each(function(){
      var that = this,
          url = $(this).attr( options.attr );
       
      // Fetch long URL and call `lengthen` when done.
      $.longUrl( url, function( long_url ){
        options.lengthen.call( that, long_url );
      });
    });
  };
   
  // Some sensible defaults.
  $.fn.longUrl.options = {
    attr: 'href',
    lengthen: function( url ) {
      $(this).attr( "title", url );
    }
  };
   
})(jQuery);

// Wouldn't you much rather do this?
$("a").longUrl();