Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 56 ยท Effects and Animation

Custom Animations with .animate()

Master jQuery .animate(): numeric properties, relative values, per-property easing, step and progress callbacks, color limits, fx.off and scrollTop.

Every effect you met so far, from .show() to .slideToggle(), is built on one method: .animate(). It takes a set of CSS properties and gradually changes the element from its current values to the ones you give. When the ready-made effects do not fit, such as moving a box across the page, growing something while dimming it or counting a number up, .animate() is the tool.

The method is simple to call but has a few rules that explain most surprises: only numeric properties move, positioning matters, and colors need help. This lesson covers those rules and the options that give you control over every frame.

What .animate() needs

Target values An object of CSS properties.
Numbers Only numeric properties can move.
Timing Duration, easing and a callback.
1 / 2

The basic call

JavaScript
$("#box").animate({ width: 300, opacity: 0.5 }, 800, "swing", function () {
  console.log("done");
});

The first argument is an object of target values. Numbers are treated as pixels (except for properties such as opacity that have no unit). The second, third and fourth arguments are the same duration, easing and callback you already know. The same call can be written with an options object, which is clearer once there are several settings:

JavaScript
$("#box").animate(
  { width: 300, opacity: 0.5 },
  { duration: 800, easing: "linear", complete: function () { /* ... */ } }
);

Property names use camelCase (fontSize, marginLeft). Dashed names are accepted when quoted, but camelCase keeps the code consistent with .css().

Positioning

Setting left or top on a statically positioned element has no effect in CSS, so animating them does nothing either. Give the element position: relative, absolute or fixed first. Properties like width, height, opacity and margins work on any element.

Units and special values

You can write values as strings with units, for example "50%" or "2em". Three keywords are also accepted: "show", "hide" and "toggle". They animate the property to or from its natural value, which is how .fadeIn() and friends are built: .animate({ opacity: "toggle" }).

Relative values

A value starting with += or -= is applied relative to the current value, which is ideal for buttons that nudge things.

JavaScript
$("#box").animate({ left: "+=50" }, 300);   // 50 px to the right of wherever it is now
$("#box").animate({ left: "-=50" }, 300);
Move and grow with relative values

Clicking quickly queues the animations one after another. That is useful, but it can also cause pile-ups; The Animation Queue explains how to control it.

Easing, including per property

The easing argument works just as in the previous lesson ("swing" or "linear"). .animate() additionally lets you choose easing for individual properties in two ways. Give an array of [target, easing], or use the specialEasing option.

JavaScript
$("#box").animate(
  { left: [300, "linear"], top: [120, "swing"] },
  1000
);

$("#box").animate(
  { left: 300, top: 120 },
  { duration: 1000, specialEasing: { left: "linear", top: "swing" } }
);

The box now travels along a curved path, because the two axes accelerate differently.

Watching the animation: step and progress

Two options let you run code during the animation, not just at the end.

  • step: function (now, fx) runs for every property of every element at every frame. now is the current value, fx.prop the property name and fx.elem the element.
  • progress: function (animation, progress, remainingMs) runs once per frame per element. progress goes from 0 to 1.

step has a surprising second use. .animate() can animate any JavaScript object, not just DOM elements, so you can animate a plain number and use step to display it. This is how counters work.

A counting number with step and progress

$({ n: 0 }) wraps a plain object. jQuery animates its n property from 0 to 1000 and calls step each frame. In complete, this is that object.

Colors cannot be animated

The core library animates numbers. A value like "red" or "#ff8800" cannot be interpolated, so { backgroundColor: "#ff0000" } does not give a smooth fade in core jQuery, and the result is unreliable. There are three clean solutions:

  1. Use a CSS transition. Add a class with .addClass() and let CSS handle the color change.
  2. Load the jQuery Color plugin or jQuery UI, which add color animation.
  3. Animate a number with step and compute the color yourself.

The first option is nearly always the best choice today.

Global switches

Two settings on the jQuery.fx object affect every animation on the page.

  • jQuery.fx.off = true makes all animations finish instantly (duration 0). Use it in automated tests, or to honor a visitor who prefers reduced motion: if (matchMedia("(prefers-reduced-motion: reduce)").matches) { jQuery.fx.off = true; }.
  • jQuery.fx.interval was the number of milliseconds between frames (default 13). Since jQuery 3 animations use requestAnimationFrame, so the property is deprecated and changing it has no practical value. You will see it in older code; leave it alone.

Animating the scroll position

Scrolling is just a numeric property, so .animate() can do smooth scrolling: scrollTop and scrollLeft are accepted.

JavaScript
$("html, body").animate({ scrollTop: $("#section3").offset().top }, 600);

Selecting both html and body covers browsers that disagree on which one scrolls the page. In modern browsers the CSS scroll-behavior: smooth or element.scrollIntoView({ behavior: "smooth" }) does the same without jQuery. The demo below scrolls a container, which works everywhere, including inside this sandbox.

Animated scrollTop in a container

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $('#box').animate({ left: '+=50' }) do?

    A value starting with += or -= is relative to the current value, so repeated calls keep moving the element.
  2. 2. Why does animating left on a default <div> appear to do nothing?

    left and top only affect positioned elements. Set position first, then animate.
  3. 3. What is the best modern way to fade a background color?

    Core jQuery animates numbers only. A CSS transition triggered by a class change handles colors without extra plugins.
  4. 4. What does the step callback receive?

    step runs for every animated property at every frame, which makes it suitable for counters and custom rendering.

Summary

  • .animate(properties, duration, easing, complete) moves numeric CSS properties toward target values; an options object is the clearer form for many settings.
  • += and -= give relative movement; "show", "hide" and "toggle" are special values; left and top need a positioned element.
  • Use [value, easing] or specialEasing to give each property its own easing.
  • step and progress run during the animation; animating $({ n: 0 }) powers counters.
  • Colors are not animatable in core: use CSS transitions or a plugin.
  • jQuery.fx.off = true disables animations globally; jQuery.fx.interval is deprecated. scrollTop can be animated.

Continue with The Animation Queue to learn how animations line up and how to stop them.