jQuery: image animation

Bringing life into web pages is one of the most common tasks of the jQuery library and its animate() method. We can actually animate images through this method by adding some nice effects to them. Suppose that we have an image preview and we want to animate the image when a user clicks on the image. First of all, some basic CSS setup:

#gallery {

    width: 70%;
    margin: 0 auto;
    padding: 2em 0;


#gallery  img {

    display: block;
    width: 100%;
    cursor: pointer;
    margin: 0 auto;


The automatic margins set on the image allow us for centering the image within its container. Now let's add jQuery:

$(document).ready(function() {

   $('#gallery img:first-child').click(function() {
       var $img = $(this);
       var width = $img.width();
       var height = $img.height();
              height: height / 2,
              width: width / 2
          }, 'slow', function() {$img.fadeTo('slow', '0.5');}).animate({
              height: height,
              width: width
          }, 'slow');

The image dimensions are first reduced, then get back to normal and finally its opacity is adjusted so that it looks semi-transparent. We've used animation chaining here, so when an animation ends another one is just starting. You can see this demo 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.