jQuery: advanced fading effect

jQuery: advanced fading effect

An advanced jQuery fading effect which divides the target content in several blocks and animates them.

I'm currently finishing the preparatory steps for a new WordPress project which heavily relies on jQuery to create advanced effects on images. A couple of weeks ago I found an interesting content slider which features some advanced fading effects both on text contents and images. Such effects are created by adding extra empty elements to each slide block. Once added, these elements are later animated using the chaining methods of jQuery. Let's see how to reproduce these effects.

I'm going to use the simplest markup structure possible just to highlight the main effect:

<div id="img">
	<img src="img14.jpg" />
</div>​

In our CSS styles we need to specify the rules for the overlaying container and its empty child elements. These elements will have a full background color to properly cover the image once showed:

#img {
    width: 550px;
    height: 330px;
    margin: 2em auto;
    position: relative;
}

#img img {
    display: block;
    position: absolute;
}

div.piece-wrapper {
    width: 100%;
    height: 100%;
    position: absolute;
    display: none;
}

div.piece {
    width: 10%;
    height: 10%;
    background: #fff;
    float: left;
    display: none;
}
​

Each block is 10% wide and 10% tall with respect to the whole containing block. Using percentages allows us to use this technique without worrying too much about the image dimensions.

With jQuery we have to create 100 blocks first, and then animate them using the animation queue provided by jQuery:

var sliceImage = function(target) {

    target = $(target);
    var i, len = 100,
        delay = 0;

    $('<div class="piece-wrapper"/>').
    appendTo(target);

    for (i = 0; i < len; i++) {

        $('div.piece-wrapper', target).
        append('<div class="piece"></div>');

    }



    $('div.piece-wrapper', target).show();
    $('div.piece', target).each(function() {

        $(this).queue('show', function(next) {

            $(this).delay(delay).show(15, next);

        });

        $(this).dequeue('show');

        delay += 10;

    });


};


setTimeout(sliceImage('#img'), 2000);

The execution of each animation has been delayed by a progressive time value so that the final effect is progressive and not simultaneous. You can see the demo below.

Demo

Live demo