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 = {},
// The API URL.
api = 'http://www.longurlplease.com/api/v1.1?callback=?';
$.longUrl = function( url, 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( {}, $.longUrl.options, options );
return this.each(function(){
var elem = $(this),
url = elem.attr( options.attr );
// Fetch long URL and call `lengthen` when done.
$.longUrl( url, function( long_url ){
options.lengthen( elem, long_url );
});
});
};
// Some sensible defaults.
$.longUrl.options = {
attr: 'href',
lengthen: function( elem, url ) {
// Update the element's title attribute with `url`.
elem.attr( 'title', url );
}
};
})(jQuery);