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)
// Store fetched long URLs here.
var cache = {};
jQuery.fn.longUrl = function() {
return this.each(function(){
var elem = jQuery(this),
href = elem.attr( 'href' ),
api = 'http://www.longurlplease.com/api/v1.1?callback=?';
if ( cache[ href ] ) {
// URL exists in cache, so use it.
elem.attr( 'title', cache[ href ] );
} else {
// Fetch JSON data.
jQuery.getJSON( api, { q: href }, function(data){
if ( data[ href ] ) {
// If the data is valid, update the cache.
cache[ href ] = data[ href ];
// Update the element's title attribute.
elem.attr( 'title', cache[ href ] );
}
});
}
});
};