A Guide to the jQuery animate() Method

Aurelio De Rosa
Share

jQuery is a lovely library, and for many years now it has changed the way thousands of developers approached their projects. When jQuery was created, CSS wasn’t able to create complex animations, leaving JavaScript as the way to go. jQuery helped a lot with animations thanks to the several methods created for this purpose. Although it comes with a few simple animations (fadeIn(), hide(), slideDown(), and so on), to keep its weight low, the library provides a very flexible method called animate(), which allows us to create any animation we desire. This method is the topic of this article.

jQuery’s animate() is a wrapper method, meaning that it operates on a set of previously selected DOM elements, wrapped by jQuery. This method allows you to apply your own custom animation effects to the elements in the set. To do that, we have to provide a set of CSS style properties and values that those properties will reach at the end of the animation. The intermediate values that the style achieves during the effect (automatically handled by the animation engine) are determined by the duration of the effect and the easing function, two options we’ll discuss soon.

The list of CSS style properties that can be animated is limited to those that accept numeric values. The value can be an absolute value (like 200), or a relative value from the starting point. In the case of an absolute value, jQuery assumes pixels as the default unit. We can also specify other units like em, rem, or percentages. To specify relative values, we have to prefix it with += or -= to indicate relative target values in the positive or negative direction, respectively.

Now that we know a little about animate(), it’s time to look at its signatures and its parameters.

Signatures and Parameters

This method comes in two main forms, and most of its parameters are optional (denoted using the usual square brackets):

  • animate(properties[, duration][, easing][, callback])
  • animate(properties[, options])

There is also a lot to say about the parameters:

  • properties (Object): A hash containing the values that should be reached at the end of the animation.
  • duration (Number|String): The duration of the effect in milliseconds or one of the predefined strings: “slow” (600ms), “normal” (400ms), or “fast” (200ms). The default is “normal”.
  • easing (String): The easing function name to use when performing the transition. The default value is “swing”.
  • callback (Function): A function to execute when the animation is completed for each animated element.
  • options (Object): A hash containing a set of options to pass to the method. The options available are the followings:
    • always (Function): A function called when the animation completes or stops without completing.
    • complete (Function): A function executed when the animation is completed.
    • done (Function): A function called when the animation completes.
    • duration (String|Number): Same as previously described.
    • easing (String): Same as previously described.
    • fail (Function): A function executed when the animation fails.
    • progress (Function): A function run after each step of the animation. The function is called only once per animated element.
    • queue (Boolean): If the animation has to be placed in the effects queue (more on this in a few moments). The default value is true.
    • specialEasing (Object): A hash of one or more CSS properties whose values are easing functions.
    • start (Function): A function executed when the animation begins.
    • step (Function): A function to invoke for each animated property of each animated element.

The term easing is used to describe the manner in which the processing and pace of the frames of the animation are handled. The queue option allows us to run animations in sequence when it’s set to true, or in parallel when set to false. That’s quite a lot of power in our hands that we can use as we like.

In the remainder of this article, we’ll demonstrate some of these arguments in action to give you a taste of what’s possible with animate().

Example Uses

In this section we’ll build some demos to unleash the power of animate(). Keep in mind that this method isn’t a good fit for very, very complex animations because of issues concerning the performance and the smoothness of the animations.

Running a Single Animation

Running a single animation is pretty easy, and involves just one call of the method. For example, we may want to move an element from one side of a box to the other. To illustrate this animation we’ll set up two div elements, one inside the other. We’ll style them so that the inner div has a red background. The code to complete this is shown below.

The HTML:

<div class="rectangle">
   <div class="square-small"></div>
</div>

The CSS:

.rectangle
{
   width: 300px;
   height: 20px;
   display: block;
   position: relative;
   border: 1px solid black;
   margin: 20px 0;
}

.square-small
{
   display: block;
   width: 20px;
   height: 20px;
   position: absolute;
   background-color: red;
}

With this markup and CSS in place, using the power of animate(), we’ll move the small square from one side to another:

$('.rectangle')
   .find('.square-small')
   .animate({
      left: 280
    }, 'slow');

In this code, we specify that the left property is the only one to animate. We set the duration of the animation to the preset value, slow (600ms). We move the inner <div> (having class .square-small) using an absolute value. The value is based on the width of the container we set using the CSS code listed before. This solution isn’t very flexible because if we change the width of the container, the inner <div> won’t reach the other side (in case we set a wider width on the container), or will pass it (in case we set a narrower width). A solution is to set the value of the left property, based on the calculation of the current widths of the outer and inner <div>s, is as follows:

left: $('.rectangle').width() - $('.rectangle').find('.square-small').width()

This example is available as a JSbin:

Basic example of using jQuery’s animate()

Running Multiple Animations in a Loop

Performing multiple animations on one element or a set of elements is as easy as chaining calls to animate(). In this example, we’ll move a small square as it’s following the perimeter of a hourglass inside a big square (instead of the rectangle). To build this demo we’ll use the following markup:

<div class="square-big">
   <div class="square-small"></div>
</div>

For the style, we need to use the same CSS used before for .square-small, and the following to style the outermost square:

.square-big
{
   width: 300px;
   height: 300px;
   display: block;
   position: relative;
   border: 1px solid black;
   margin: 20px 0;
}

The last step is to write the JavaScript code to draw the four lines that compose the perimeter of our ideal hourglass. Starting from the top-left of the outermost square, we have to animate the small square until it reaches the bottom-right angle of the big square. The small square has to move on a diagonal to create the effect. Once it reaches the bottom-right angle, we have to move it to the bottom-left angle. Then, it has to reach the top-right angle, and finally go back to its original position.

When introducing this demo, we said that we want to perform an infinite animation. So, we have to find a way to run the whole animation again, once completed the last step. To do so, we can wrap the call to the four chained call to animate() inside a function, so we have a function to refer to. Then, we can use the complete callback we’ve mentioned before and an IIFE to run again the animation when the last step is completed. Translating this description into code results in:

(function animation() {
   var options = {
      duration: 800,
      easing: 'linear'
   };

   $('.square-big')
      .find('.square-small')
      .animate({
            left: 280,
            top: 280
         },
         options
      )
      .animate({
            left: 0,
         },
         options
      )
      .animate({
            left: 280,
            top: 0,
         },
         options
      )
      .animate({
            left: 0,
         },
         $.extend(true, {}, options, {
            complete: function() {
               animation();
            }
         })
      );
})();

In the code above, note how we used an options variable so we don’t have to write the same parameters over and over again when calling animate(). In addition, because the last time we used options we have to add the complete callback, we employ the jQuery’s extend() method.

This example is available as a JSbin:
Creating infinite animations with jQuery’s animate()

More Callbacks to Action

As our last example, we’ll set the start, complete, and progress properties of the options parameter (the second parameter of the second form). The scope is to disable the button that when clicked runs the animation when the animation is running. After that we want to show a percentage of the animation’s completeness. For this example, we’ll modify the first demo we built.

Based on the description, we have to add a button and an element (we’ll employ a span) to show the percentage. This changes results in the following markup:

<div class="rectangle">
   <div class="square-small"></div>
</div>
<button id="animation-button">Run!</button>
<span id="percentage">0</span>%

We don’t have to add more style, so we can jump to the discussion of the JavaScript code. To run the animation only when the button is clicked, we have to add a handler to the click event of the button. Inside the handler we disable and enable the button using jQuery’s prop() method based on whether the animation is running or complete. Finally, we use the second argument passed to the handler attached to the progress option to show the percentage of completeness of the animation. The resulting code is listed below:

$('#animation-button').click(function() {
   var $button = $(this);

   $('.rectangle')
      .find('.square-small')
      .animate({
            left: 280
         },
         {
            duration: 2000,
            start: function() {
               $button.prop('disabled', true);
            },
            complete: function() {
               $button.prop('disabled', false);
            },
            progress: function(animation, progress) {
               $('#percentage').text(Math.round(progress * 100));
            }
         }
      );
});

This example is available as a JSbin:
Putting into action some jQuery’s animate() callbacks

Conclusion

This article discussed what we can do using jQuery’s animate() method. We introduced its signatures and the parameters it accepts. During the article we explored three example animations. This article has only skimmed the surface of what’s possible with animate(). In fact, with a bit of patience and creativity we can create really complex and nice animations. An example of what you can do is the Audero Smoke Effect, a jQuery plugin that I developed to create a smoke effect for one or more elements, usually images, on a web page. With it, you can create the effect of a little smoke puff, cloud or anything else you want that appears from the elements you choose.