How to Use jQuery animate() for CSS Properties

The jQuery animate() method allows you to create custom animations by gradually transitioning an HTML element from one set of CSS styles to another. This article explains the syntax of the animate() method, how to manipulate single and multiple numeric CSS properties, use relative and predefined values, and manage animation queues with callback functions.

Basic Syntax of the animate() Method

The standard syntax for the animate() method is as follows:

$(selector).animate({ params }, speed, easing, callback);
  • params (required): Defines the CSS properties to be animated as a JavaScript object.
  • speed (optional): Specifies the duration of the effect. Can be set to 'slow', 'fast', or a time in milliseconds (e.g., 1000).
  • easing (optional): Specifies the speed of the animation at different points. Default values are 'swing' and 'linear'.
  • callback (optional): A function to be executed after the animation completes.

Supported CSS Properties

The core jQuery animate() method only animates properties that accept numeric values. Properties such as width, height, margin, padding, top, left, fontSize, and opacity can be animated.

Non-numeric properties, such as backgroundColor or color, cannot be animated with standard jQuery alone and require the jQuery UI library or a dedicated color animation plugin. When defining CSS property names with hyphens (like font-size or margin-left), use camelCase format (fontSize, marginLeft) or wrap the property name in quotes.

Animating Multiple Properties

You can animate multiple CSS properties simultaneously by defining them within the same object:

$("button").click(function() {
    $("#box").animate({
        left: "250px",
        opacity: 0.5,
        height: "150px",
        width: "150px"
    }, 800);
});

Note: For properties like left, top, right, or bottom to take effect, ensure the target element has its CSS position set to relative, absolute, or fixed.

Using Relative Values

You can specify values relative to the element's current value by prefixing the target value with += (increment) or -= (decrement):

$("#box").animate({
    left: "+=50px",
    height: "-=20px"
}, "fast");

Using Pre-defined Values

jQuery supports pre-defined animation values, such as "show", "hide", or "toggle", allowing you to animate dimensions to reveal or collapse elements:

$("#box").animate({
    height: "toggle",
    opacity: "toggle"
});

Queueing Animations and Callbacks

By default, if you write multiple animate() calls in succession, jQuery queues them and executes them one after another. If you need a specific action to occur immediately after an animation finishes, pass a callback function:

$("#box").animate({ height: "300px" }, "slow")
         .animate({ width: "300px" }, "slow", function() {
             console.log("Animation sequence complete.");
         });