Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created July 12, 2010 17:36
Show Gist options
  • 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 = {};
$.longUrl = function( url, callback, options ) {
// Override defaults with specified options.
options = $.extend( {}, $.longUrl.options, options );
var params = {};
if ( cache[ url ] ) {
// URL exists in cache, so use it.
callback( cache[ url ] );
} else {
params[ options.param ] = url;
// Fetch JSON data.
$.getJSON( options.api_url, params, 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 );
}, options );
});
};
// Some sensible defaults.
$.longUrl.options = {
api_url: 'http://www.longurlplease.com/api/v1.1?callback=?',
param: 'q',
attr: 'href',
lengthen: function( elem, url ) {
// Update the element's title attribute with `url`.
elem.attr( 'title', url );
}
};
})(jQuery);