Skip to content

Instantly share code, notes, and snippets.

@sentientmonkey
Created August 19, 2011 21:55
Show Gist options
  • Save sentientmonkey/1158116 to your computer and use it in GitHub Desktop.
Save sentientmonkey/1158116 to your computer and use it in GitHub Desktop.
javascript/jquery crossfader for tiled images
(function($) {
// crossfade takes an image list, which is an array of hashes with
// src: image url
// title: link title
// href: link url
//
// available options:
// fadeTime: time in msec of how long cross fade transition takes
// waitTime: time in msec of how long to wait between transitions
// imageHeight: height of each image
// imageWidth: width of each images
// tiles: how many visible tiles to display
// imageClass: css class for each image
$.fn.crossfade = function(image_list, options) {
defaults = {
fadeTime: 2000,
waitTime: 4000,
imageWidth: 100,
imageHeight: 100,
imageClass: 'fade-image',
tiles: 9
};
var settings = $.extend({}, defaults, options);
var self = $(this);
var init_pos = settings.tiles;
// cross-fading is done as a follows:
// - clone existing image
// - set relative positioning, z-index in front, opacity 0, top height of image
// - append to link tag
// - update title & url
// - animate opacity of new image to 1
// - remove old image
// - update new image z-index & top
function fade(){
init_pos = (init_pos + 1) % image_list.length;
var cat = image_list[init_pos];
var swapPos = Math.floor(Math.random()*(settings.tiles-1));
var link = $(self.find('a.' + settings.imageClass)[swapPos]);
if(link){
var img = link.find('img');
var new_img = img.clone();
new_img.attr('src', cat.src);
new_img.css({position: 'relative',
left: 0,
top: '-' + settings.imageHeight + 'px',
'z-index': 1000,
opacity: 0
});
link.append(new_img);
link.attr('href', cat.href);
link.attr('title', cat.title);
link.find('img:last').animate({opacity: 1}, settings.fadeTime, function(){
img.remove();
$(this).css({top: 0,
'z-index': 0});
setTimeout(fade, settings.waitTime);
});
}
}
function init(){
for(var i=0; i < settings.tiles; i++){
var c = image_list[i];
var link = $('<a></a>');
link.attr('href', c.href);
link.attr('title', c.title);
link.addClass(settings.imageClass);
var img = $('<img />').attr('src', c.src);
img.attr('width', settings.imageWidth);
img.attr('height', settings.imageHeight);
link.html(img);
self.append(link);
}
setTimeout(fade, options.waitTimeout);
}
init();
return self;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment