Skip to content

Instantly share code, notes, and snippets.

@matteodelabre
Last active August 29, 2015 14:04
Show Gist options
  • Save matteodelabre/83734953ee3d264918b8 to your computer and use it in GitHub Desktop.
Save matteodelabre/83734953ee3d264918b8 to your computer and use it in GitHub Desktop.
jQuery plugin that permits elements crossfading

Crossfade

jQuery plugin that permits crossfading between HTML elements. Mostly for images but can also work for other types, such as divs that contain images in background or in subtree.

How to use:

$('.element-containing-elements-to-crossfade').crossfade();

Parameters

  • speed: transition speed
  • duration: how much time an element stays displayed

License

None, do what you want.

.crossfade > * {
display: none;
}
.crossfade > .show {
display: block;
}
/*jslint browser: true */
/*globals jQuery */
(function ($) {
'use strict';
$.fn.crossfade = function (params) {
var defaults = {
speed: 500,
duration: 10000
};
params = $.extend(defaults, params);
$(this).each(function () {
var el = $(this), images = el.children(),
length = images.length, i = length - 1,
duration = params.duration,
speed = params.speed;
(function change() {
images.slice(i, i + 1).fadeOut(speed);
i += 1;
if (i >= length) {
i = 0;
}
setTimeout(function () {
images.slice(i, i + 1).fadeIn(speed);
}, speed / 2);
setTimeout(change, duration);
}());
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment