jQuery: cross-fading blocks

jQuery: cross-fading blocks

How to create the effect of cross-fading HTML blocks with jQuery.

The cross-fading technique is pretty popular among jQuery developers. Simply put, you have only to stack a series of parallel blocks with absolute positioning, adjust their layering index with jQuery and use intervals to create the cross-fading effect.

We have the following structure:


<div class="fade-blocks-wrapper">
	<div class="fade-block">
		<div class="block">1</div>
		<div class="block">2</div>
	</div>
	<div class="fade-block">
		<div class="block">3</div>
		<div class="block">4</div>
	</div>
	<div class="fade-block">
		<div class="block">5</div>
		<div class="block">6</div>
	</div>
</div>

With CSS we can stack each block one on the top of the other:


.fade-blocks-wrapper {
	width: 560px;
	height: 180px;
	margin: 2em auto;
	position: relative;
	overflow: hidden;
}

.fade-block {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
}
.fade-block .block {
	width: 250px;
	height: 100%;
	margin: 0 10px;
	background: #eee;
	float: left;
	line-height: 180px;
	text-align: center;
	font-size: 2em;
}

.fade-block:nth-child(2) .block {
	background: #666;
	color: #fff;
}

.fade-block:nth-child(3) .block {
	background: #ffc;
}

Then with jQuery we adjust the z-index property and use JavaScript intervals to create the cross-fading effect:


(function($) {
	$.fn.rotator = function(options) {
		options = $.extend({
			blocks: '.fade-block',
			speed: 1000
		}, options);
		var setZIndex = function(element) {
				var index = $(options.blocks, element).length;
				$(options.blocks, element).each(function() {
					index--;
					$(this).css('zIndex', index);
				});
			};
		var rotate = function(element) {
				var blocks = $(options.blocks, element),
					len = blocks.length,
					index = -1;
				blocks.fadeIn(options.speed);
				var timer = setInterval(function() {
					index++;
					var block = blocks.eq(index);
					if (index == len) {
						clearInterval(timer);
						rotate(element);
					}
					if (block.index() != (len - 1)) {
						block.fadeOut(options.speed);
					}
				}, options.speed);
			};
		return this.each(function() {
			var elem = $(this);
			setZIndex(elem);
			rotate(elem);
		});
	};
})(jQuery);

We can use our code as follows:


$(document).ready(function() {
	$('div.fade-blocks-wrapper').rotator({
		speed: 2500
	});
});

[view-example url="http://jsfiddle.net/gabrieleromanato/EaxKs/"]