Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created July 12, 2010 17:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cowboy/472783 to your computer and use it in GitHub Desktop.
Save cowboy/472783 to your computer and use it in GitHub Desktop.
jQuery Pluginization (see comment for slide order)
(function($){
// Store fetched long URLs here.
var cache = {};
$.fn.longUrl = function( attr ) {
return this.each(function(){
var elem = $(this),
url = elem.attr( attr || 'href' ),
api = 'http://www.longurlplease.com/api/v1.1?callback=?';
if ( cache[ url ] ) {
// URL exists in cache, so use it.
elem.longUrlLengthen( 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 `longUrlLengthen` for this element + long url.
elem.longUrlLengthen( cache[ url ] );
}
});
}
});
};
$.fn.longUrlLengthen = function( url ) {
// Update the element's title attribute with `url`.
return this.attr( 'title', url );
};
})(jQuery);