jQuery: animation steps

The jQuery's animate() method provides, among its options, also a step() method to control each animation step. This method is called each time a step is completed. To use this method, we have to write the animate() method with its extended syntax that includes, in addition to the first object containing style properties, another object called options. So instead of writing this method with the following syntax:

$(element).animate({
  property: value
}, 1000, function() {
  alert('Complete');
});

we should write:

$(element).animate({
  property: value
},
{
  duration: 1000,
  
  complete: function() {
  
    alert('Complete');
  
  }
}
);

that is, using the options object. In fact, the step() method can be called within this object. An example:

var width = 0;

  $('#run').click(function(e) {
  
    $('#test').animate({
      width: '+=20px',
      height: '+=20px',
      left: 30
    },
     
    
   { 
   step: function() {
     
     
     $('#results').css('width', width += 1).html('Step ' + width);
     
     
   },
   
   duration: 1000,
   
   complete: function() {
   
     $(this).animate({
       width: '-=20px',
       height: '-=20px',
       left: 0
     },
     
     {
     
       step: function() {
       
         $('#results').css('width', width -= 1).html('Step ' + width);
         
       },
       
       duration: 1000
     
     
     }
     
     
    );
   }
   }
   
   
   );
   
     
  e.preventDefault();
  });

This method is called for each step. The counter width keeps track of the number of steps within an animation whose time span is 1000 milliseconds. We have three style properties affected here, so our counter will also keep track of the steps contained in each modification of a single style property. You can see the example below.

Example

Live example

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.