Sep 10, 2011

Easter egg on the blog: A small trick using CSS

Update (09/28/2011): After enabling the newly released "Dynamic Views" on the blog, I lost the ability to reference jQuery from inside the HTML code of the blog, so the trick doesn't work anymore here. Anyway, you can still use the above code in your own website to make it happen.

I know you haven't noticed it yet. Go to the About myself page, and click on the image you will see there. Nice uh? The transition between the images is pretty simple to reproduce. Let's start with the HTML code:
<div id="pictures">
    <img class="image-0" src="image-0.jpg" />
    <img class="image-1 transparent" src="image-1.jpg" />
    <img class="image-2 transparent" src="image-2.jpg" />
</div>
Pretty straightforward: three images inside a div, and two of them using the class transparent. In reality I'm using five different images, but I just described three on the example above to make things simpler. Now let's take a look to the CSS code:
#pictures {
    position:relative;
    margin:0 auto;
}
#pictures img {
    position:absolute;
    left:0;
    transition: opacity 1s ease-in-out;
}

#pictures img.transparent {
    opacity:0;
}
Here is where all the magic happens. Using the new CSS3 transition element, I'm specifying that whenever this class becomes active, it should transition the opacity property from its current value to the one specified by the new class, taking 1 second to do the animation and using ease-in-out as the timing function.

Without expanding too much on how "transition" works on CSS3, as soon as you switch classes on the image element (between transparent and the default one), a 1 second animation will occur on the opacity property.

To kick off the animation on the click event, we will need a little bit of JavaScript:
var currentImage = 0;
$(document).ready(function() {
    $("#pictures img").click(function() {
        $("#pictures img").addClass("transparent");
        currentImage = (currentImage + 1) % 3;
        $("#pictures img.image-" + currentImage).removeClass("transparent");
    });
}); 
As you can see, I'm just "moving" the default class around the three images by removing the class transparent. This will cause the active image to fade in and the previous one to fade out.

Simple, but very good looking.