jQuery: animating images

Animating images with jQuery is a pretty simple and amusing task. For example, we can start with the following markup:

<ul id="image-gallery">

<li><img src="img/1.png" alt="A boat" />
<div class="caption">A boat</div></li>
<li class="vertical-center"><img src="img/2.png" alt="A typewriter" />
<div class="caption">A typewriter</div></li>

</ul>

This is a basic image gallery. We can add some CSS styles:

#image-gallery {

    width: 410px;
    margin: 0 auto;
    padding: 5px 0;
    border-top: 5px solid #999;
    border-bottom: 3px solid #999;
    list-style: none;
    height: 100%;
    overflow: hidden;

}

#image-gallery li {

    float: left;
    margin-right: 5px;
    width: 200px;

}

#image-gallery li img {

    display: block;
    width: 200px;
    cursor: pointer;

}

#image-gallery li.vertical-center {

    padding-top: 50px;

}

#image-gallery li div.caption {

    width: 200px;
    margin: 4px 0;
    padding: 3px 0;
    border-top: 1px dashed #999;
    border-bottom: 1px dashed #999;
    

}

Now it's time to add some behavior with jQuery:

$(document).ready(function() {


    $('#image-gallery li img').each(function() {
    
    
        var $img = $(this);
        var imgWidth = $img.width();
        var imgHeight = $img.height();
        
        
        $img.mouseover(function() {
        
            $img.animate({opacity: 0.5, width: imgWidth / 2, height: imgHeight /2}, '600');
        
        
        });
        
        $img.mouseout(function() {
        
            $img.animate({opacity: 1, width: imgWidth, height: imgHeight}, '600');
        
        });
    
    
    });


});

We iterate over each image within our gallery. We store the actual dimensions of each image in two separate variables. Then we attach mouseover and mouseout events to the images. Either an user moves his/her mouse over or out the image box, we use the animate() method to adjust the image's opacity, width and height. You can see the final result here.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.