jQuery Queued Animations Syntax Guide

This guide covers how to sequence animations in jQuery using its built-in animation queue. By default, jQuery executes animation effects consecutively on the same element via method chaining. You will learn the basic syntax for chaining animations, how to insert custom functions into the queue with the .queue() method, and how to sequence animations across multiple distinct elements using callbacks and promises.

1. Basic Chaining on the Same Element

When applying multiple animation methods to a single jQuery object, jQuery automatically places them into an internal animation queue named fx. Each animation starts only after the previous one finishes.

$("#box")
  .animate({ left: "200px" }, 1000)
  .animate({ top: "100px" }, 800)
  .slideUp(500)
  .slideDown(500);

2. Inserting Custom Functions with .queue()

Standard non-animation jQuery methods (such as .css() or .addClass()) do not wait for animations to finish by default. To insert a non-animation action into the sequence, use the .queue() method and call next() to pass execution to the subsequent queued item.

$("#box")
  .animate({ width: "300px" }, 1000)
  .queue(function(next) {
    $(this).css("background-color", "red");
    next(); // Required to continue the animation sequence
  })
  .animate({ height: "300px" }, 1000);

3. Sequencing Across Different Elements Using Callbacks

Because separate elements maintain separate queues, method chaining will not sequence animations across different selectors. To run animations sequentially across different elements, place the subsequent animation inside the complete callback function of the .animate() method.

The syntax for .animate() with a completion callback is:

$(selector).animate({ styles }, speed, easing, callback);

Example:

$("#firstElement").animate({ opacity: 0 }, 1000, function() {
  $("#secondElement").animate({ opacity: 1 }, 1000, function() {
    $("#thirdElement").slideDown(500);
  });
});

4. Sequencing Across Elements Using Promises

To avoid deeply nested callbacks (callback hell), use jQuery's .promise() and .then() methods:

$("#firstElement").animate({ opacity: 0 }, 1000).promise()
  .then(function() {
    return $("#secondElement").animate({ opacity: 1 }, 1000).promise();
  })
  .then(function() {
    return $("#thirdElement").slideDown(500).promise();
  });

Controlling the Queue

  • .delay(duration): Inserts a timed pause between animations in the queue.
  • .stop(clearQueue, jumpToEnd): Stops the currently running animation on an element. Setting clearQueue to true cancels all remaining animations in the sequence.
  • .finish(): Stops the current animation, removes all queued animations, and instantly jumps all animations to their final property values.