jQuery animate Step Function Explained

The step function in jQuery's animate() method is an optional callback that executes on every step—or frame—of an animation for each animated CSS property. It grants real-time access to the current state of the animation, enabling developers to modify behavior mid-flight, animate non-standard attributes like CSS transforms, build synchronized visual effects, or animate plain numeric values for counters and progress indicators.

Syntax and Parameters

To use the step function, pass it as part of the options object in a call to animate():

$("#element").animate(
  {
    opacity: 0.5,
    top: "+=100px"
  },
  {
    duration: 1000,
    step: function(now, fx) {
      // Logic executed on every frame per property
    }
  }
);

The function accepts two arguments:

  • now: A floating-point number representing the current numeric value of the animated property at that specific frame.
  • fx: A jQuery internal Tween/FX object containing metadata about the current animation step, including:
    • fx.prop: The name of the property currently being animated (e.g., "opacity" or "top").
    • fx.elem: The DOM element being animated.
    • fx.start: The starting value of the animation.
    • fx.end: The target ending value.
    • fx.unit: The unit of measurement (such as px, %, or "").
    • fx.pos: The relative progression of the animation from 0 to 1 (accounting for easing).

Primary Use Cases

1. Animating CSS Transforms

Standard jQuery animate() cannot interpolate string-based CSS3 properties like transform: rotate(45deg) or scale(1.5) directly. The step function bypasses this limitation by animating a dummy property or arbitrary object and applying the transform manually on every frame:

$({ deg: 0 }).animate({ deg: 180 }, {
  duration: 800,
  step: function(now) {
    $("#box").css({
      transform: "rotate(" + now + "deg)"
    });
  }
});

2. Number Counters and Progress Displays

Because jQuery can animate arbitrary numeric properties on plain JavaScript objects, step is frequently used to create animated counting numbers:

$({ count: 0 }).animate({ count: 1000 }, {
  duration: 2000,
  step: function(now) {
    $("#counter").text(Math.floor(now).toLocaleString());
  }
});

3. Real-Time Synchronization and Constraints

Unlike the complete callback—which fires once the entire animation finishes—the step function runs continuously. This allows you to update secondary UI components (like a progress bar), check for collisions, or conditionally cancel or alter the animation before it completes.

Execution Caveat

If an animation targets multiple properties on a single element (such as width, height, and top), the step function runs once for each property during every frame. If your custom logic should only run once per animation frame, evaluate fx.prop to isolate a single property.