Animate Multiple Properties with jQuery animate()
Animating multiple CSS properties at the same time using jQuery's
.animate() method is achieved by including all target
styles within a single JavaScript object passed as the first argument.
This tutorial explains how to structure your property-value pairs,
handle CSS property naming conventions, use relative values, and control
the timing to ensure all animations execute concurrently rather than
sequentially.
The Basic Syntax
To run simultaneous animations, pass all desired CSS properties
inside a single object literal to .animate().
$(selector).animate({
property1: value1,
property2: value2,
property3: value3
}, duration, easing, callback);Because all properties are defined within the same object, jQuery animates them in parallel over the specified duration.
Practical Example
The following example simultaneously changes an element's opacity, width, height, and left margin over a period of 1000 milliseconds (1 second):
$("#box").animate({
opacity: 0.5,
width: "300px",
height: "150px",
marginLeft: "50px"
}, 1000);Important Formatting Rules
When passing multiple properties to .animate(), keep the
following conventions in mind:
- CamelCase Names: CSS properties that contain
hyphens must either be written in camelCase or enclosed in quotes. For
example, use
marginLeftor"margin-left", notmargin-leftwithout quotes. - Numeric Values Only: Core jQuery can only animate
properties that accept numeric values, such as
width,height,top,left,fontSize, andopacity. Non-numeric properties (such asbackgroundColorordisplay) cannot be animated with standard jQuery unless you include the jQuery UI library or a dedicated color plugin. - Relative Values: You can adjust properties relative
to their current state by prefixing the value with
+=or-=. For example,left: "+=50px"shifts the element 50 pixels farther to the right.
Example Using Relative Values and Callbacks
You can combine relative values and a completion callback to trigger additional actions once all simultaneous animations finish:
$("#element").animate({
width: "+=100px",
height: "+=50px",
opacity: 0.8
}, 800, "swing", function() {
console.log("All properties finished animating simultaneously.");
});