jQuery Animate

jQuery Animate

The jQuery animate() method lets you create custom animations.

You can animate almost any CSS property, like width, height, or padding.

It is incredibly powerful for building unique interactive experiences.


The animate() Method Syntax

The basic syntax looks like this: $(selector).animate({params}, speed, callback);

The required params define the CSS properties you want to animate to.

Basic Animate Example:

$("button").click(function(){
  $("div").animate({left: '250px'});
});

Important Note: By default, HTML elements have a static position, meaning they cannot move. To animate elements physically, their CSS position property must be set to relative, fixed, or absolute!


Animating Multiple Properties

You can animate multiple CSS properties at the same exact time.

Simply separate the properties with a comma inside the curly brackets.

Notice that CSS properties must be camel-cased when written in jQuery (e.g., paddingLeft instead of padding-left).

Multiple Properties Example:

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

Using Relative Values

It is also possible to define relative values instead of absolute ones.

You achieve this by placing += or -= in front of the value.

This adds or subtracts from the element's current size or position.

Relative Value Example:

$("button").click(function(){
  // Adds 50px to the current height and width on each click
  $("div").animate({
    height: '+=50px',
    width: '+=50px'
  });
});

What Can Be Animated?

Almost all CSS properties with a numeric value can be animated.

However, you cannot animate non-numeric properties, like background-color.