A Guide to the jQuery animate() Method

Share this article

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.

Frequently Asked Questions (FAQs) about jQuery Animate Method

What is the jQuery animate method and how does it work?

The jQuery animate method is a powerful tool that allows you to create custom animations. It works by gradually changing the CSS properties of an element over a specified duration. You can animate any CSS property, but you must specify the property in camel case, for example, ‘marginLeft’ instead of ‘margin-left’. The animate method also allows you to specify easing functions, which control the speed of the animation, and callback functions, which are executed after the animation completes.

How can I stop or pause a jQuery animation?

jQuery provides the ‘stop()’ method to stop an animation. This method stops the currently running animation on the selected element. If you want to pause an animation, it’s a bit more complex because jQuery doesn’t provide a built-in method for this. However, you can achieve it by using a plugin or by manually controlling the animation’s progress.

Can I animate multiple properties at once with jQuery animate?

Yes, you can animate multiple CSS properties at once using the jQuery animate method. You just need to include all the properties you want to animate in the properties object. For example, you can animate both the width and height of an element at the same time.

How can I use the step function in jQuery animate?

The step function in jQuery animate is a callback function that is executed at each step of the animation. This function is passed two arguments: now, which is the current value of the animated property, and fx, which is an object containing information about the animation. You can use the step function to create complex animations or to debug your animations.

Can I use jQuery animate with non-numeric CSS properties?

No, the jQuery animate method only works with numeric CSS properties. If you try to animate a non-numeric property, like color or background-color, it won’t work. However, you can use plugins like jQuery UI or jQuery Color to animate these properties.

How can I chain animations with jQuery animate?

You can chain animations in jQuery by simply calling multiple animate methods one after the other. jQuery will execute the animations in the order they were called. This is known as “queueing” and it’s a powerful feature of jQuery animations.

Can I use jQuery animate to create a slide effect?

Yes, you can use the jQuery animate method to create a slide effect. You can do this by animating the height or width of an element. However, jQuery also provides the ‘slideDown’, ‘slideUp’, and ‘slideToggle’ methods, which are easier to use if you just want to create a simple slide effect.

How can I make my jQuery animations smoother?

There are several ways to make your jQuery animations smoother. One way is to use easing functions, which control the speed of the animation. Another way is to use the ‘requestAnimationFrame’ method, which allows the browser to optimize the animation. You can also improve performance by minimizing the number of DOM manipulations and by using CSS transitions where possible.

Can I use jQuery animate on a set of elements?

Yes, you can use the jQuery animate method on a set of elements. When you call the animate method on a jQuery object that contains multiple elements, the animation will be applied to all the elements in the set.

How can I use jQuery animate to create a fade effect?

You can use the jQuery animate method to create a fade effect by animating the ‘opacity’ property. However, jQuery also provides the ‘fadeIn’, ‘fadeOut’, and ‘fadeToggle’ methods, which are easier to use if you just want to create a simple fade effect.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

animationColinI
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form