jQuery: animation tutorial

jQuery animations are achieved through the animate() method combined with CSS styles. In this tutorial, we'll build a complex, sequential animation using also JavaScript timers. But first, let's take a look at the basics of jQuery animations.

CSS properties

We said earlier that the animate() method works with CSS styles. More precisely, this method works with the following CSS properties:

  1. width
  2. height
  3. margin, marginTop, marginBottom, marginLeft, marginRight
  4. padding, paddingTop, paddingBottom, paddingLeft, paddingRight
  5. opacity
  6. visibility
  7. position
  8. top, right, bottom, left
  9. lineHeight
  10. fontSize

Properties not supported or partially supported include:

  1. display
  2. border properties
  3. color
  4. background properties

The support to these properties can be achieved through plugins. In our example, we'll use the jQuery UI framework to extend the support of animate() to cover also the background-color property.

CSS values

All valid CSS values are accepted by animate(), plus three custom jQuery values:

  1. hide
  2. show
  3. toggle

The effect of these values varies from property to property. For example, the toggle value applied to visibility changes the visibility of an element according to its current state, that is, it hides the element if it's visible and vice versa. Instead, when this value is applied to the width or height property, it simply changes the dimensions of the element according to its current state.

Be aware, however, that in most cases these custom values might not work in all versions of Internet Explorer prior to 9.

The += operator

The traditional += JavaScript operator can be applied to CSS values to augment such values dynamically. For example, if you have a 200-pixels wide box and you specify width: '+=20px', then 20 pixels will be added to the global width of your box. To work properly, this operator must always be enclosed between quotes.

Units

All normal CSS units and lengths are supported. When jQuery encounters a number without a unit, it automatically computes it as pixels, so width: 200 becomes width: 200px.

animate() syntax

The basic syntax of the animate() method is as follows:

animate(cssStyles, speed, callback);
  1. cssStyles: an object literal containing comma-separated pairs of CSS properties and values:
    $('#test').animate({
      width: 200,
      height: 200,
      opacity: '0.5'
    }, speed, callback);
    

    Note that the last pair must not be followed by a comma. This parameter is required for the animation.

  2. speed: the speed of the animation, either expressed in milliseconds (e.g. 1000) or using a keyword, such as normal (default), slow and fast:
    $('#test').animate({
      width: 200,
      height: 200,
      opacity: '0.5'
    }, 2000, callback);
    

    This parameter is optional.

  3. callback: a callback function to be executed when the animation is complete:
    $('#test').animate({
      width: 200,
      height: 200,
      opacity: '0.5'
    }, 2000, function() {
    
      alert('Complete!');
    
    
    });
    

    Within this callback function, $(this) refers to the current animated jQuery object (in this example, #test). This parameter is optional.

Sequential animations

As we said earlier, animate() accepts a callback function as its third parameter. Normally, animations are a one-way process. When the animation is complete, the chain ends. We can extend the animation sequence by calling again animate() on the same jQuery element using this callback function:

$('#test').animate({
  width: 200,
  height: 200,
  opacity: '0.5'
}, 2000, function() {

  $(this).animate({
  
    opacity: '1',
    width: 100,
    height: 100
  
  
  }, 2000);


});

Further, inside the second call to animate() we can call again our callback function and add another animation to our element. And so on.

An example

For our example we need a container, an element to animate and a trigger link. The markup for our elements is really simple:

<p><a href="#" id="run">Animate</a></p>

<div id="container">
 <div id="animated"><span>Test</span></div>
</div>

Now we need to define some initial CSS styles. Since we want to move our target element, we need to use relative and absolute CSS positioning:

#container {
 width: 600px;
 height: 600px;
 position: relative;
 border: 2px solid gray;
}

#animated {
 width: 100px;
 height: 100px;
 font: 20px Arial, sans-serif;
 text-align: center;
 background: silver;
 position: absolute;
 top: 0;
 left: 0;
}

#animated span {
 display: block;
 height: 100%;
 line-height: 100px;
}

Our target element is positioned at the top left corner of our container. First, let's attach a click event to our trigger link to be fired just once:

$(document).ready(function() {

  $('#run').one('click', function(e) {
  
  
    // code here
  
    e.preventDefault(); 
  
  });

});
Step 1: move the element to the center of its container

  // code here
  
  $('#animated').animate({
    left: '50%',
    marginLeft: '-50px'
  }, 1000, function() {
  
    // continues
  
  });

This is a basic CSS technique to center an element horizontally: simply set the left property to 50% and then subtract the half of the element's width from its margin-left property.

Step 2: center the element vertically and horizontally

  // code here
  
  $('#animated').animate({
    left: '50%',
    marginLeft: '-50px'
  }, 1000, function() {
  
    // continues
    
    $(this).animate({
    
      top: '50%',
      marginTop: '-50px'
    
    
    }, 1000, function() {
    
    
      // continues
    
    });
  
  });

Another basic CSS technique to center an element vertically. It works exactly as the previous one, except that now the properties involved are top and margin-top.

Step 3: enlarge the element to full width
 // code here
  
  $('#animated').animate({
    left: '50%',
    marginLeft: '-50px'
  }, 1000, function() {
  
    // continues
    
    $(this).animate({
    
      top: '50%',
      marginTop: '-50px'
    
    
    }, 1000, function() {
    
    
      // continues
      
      $(this).animate({
      
        width: '100%',
        left: 0,
        marginLeft: 0
      
      }, 1000, function() {
        
          // continues
      
      });

    
    });
  
  });

We've reset the left and margin-left properties to avoid our element from overflowing its container.

Step 4: Change opacity and background color
// continues

$(this).animate({
          backgroundColor: 'yellow',
          opacity: '0.5'
        }, 1000, function() {

  // continues
  
    });
Step 5: Restore opacity, background color, width and augment font size
// continues
$(this).animate({
          
            opacity: '1',
            backgroundColor: 'silver',
            width: '100px',
            fontSize: '30px'
          
          
          }, 1000, function() {
          
    // continues
    
   });
Step 6: Return to the original position and restore font size
// continues
$(this).animate({
            
              top: 0,
              left: 0,
              fontSize: '20px',
              margin: 0
            
            
            }, 1000);

Self-repeating animations

So we have a six-steps animation. Each step lasts 1 second (1000 milliseconds), so we have an overall duration of 6 seconds. We can create a JavaScript timer where we can include all our previous code:

  var timer = 0;

  $('#run').one('click', function(e) {
  
  var interval = setTimeout(function() {
  
  
    timer += 1;
  
  
      
    $('#animated span').text(timer);
    
    // animation chain
    
    
    setTimeout(arguments.callee, 6000);
  
  
  }, 25);
  
  
  e.preventDefault();
  });

The first setTimeout() function creates a timer which includes all our animation chain. Instead, the second setTimeout() function calls its parent function, thus making our animation chain enter in an infinite loop. Note that the duration of this second timer is set to 6000, that is, the overall duration of our animation chain. You can see our demo below.

Demo

Live demo

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

2 thoughts on “jQuery: animation tutorial”

  1. Very good tutorial,its clear, im still trying to figure Jquery, but i really managed to follow your tutorial.Thanks Gabriele

Leave a Reply

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