← Back to jQuery Course | Chapter 4: Effects & Animations | Lesson 4 of 9

Custom Animations with animate()

animate changes numeric CSS properties over time.

Basic animate()

The animate() method smoothly transitions one or more numeric CSS properties on an element to new target values over a set duration. It only works on properties with numeric values, like width or opacity, not on colors without a plugin.

Example: Basic animate()

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box" style="width:100px">Box</div>
    <script>
      $("#box").animate({width: "300px"});
    </script>
  </body>
</html>

Multiple Properties

Passing an object with several properties, like {width: 200px, opacity: 0.5}, animates all of them together in one call, saving you from chaining multiple separate .animate() calls that would otherwise run out of sync.

Example: Multiple Properties

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box" style="width:100px;opacity:1">Box</div>
    <script>
      $("#box").animate({width: "200px", opacity: 0.5});
    </script>
  </body>
</html>

Duration

The second argument to animate() sets how long the transition takes, either as milliseconds or a keyword like slow or fast, giving you direct control over animation pacing.

Example: Duration

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box" style="width:100px">Box</div>
    <script>
      $("#box").animate({width: "300px"}, 2000);
    </script>
  </body>
</html>

Opacity

Opacity is one of the few non-pixel numeric properties animate() understands out of the box, letting you fade an element in or out as part of a larger multi-property animation.

Example: Opacity

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box">Box</div>
    <script>
      $("#box").animate({opacity: 0});
    </script>
  </body>
</html>

Relative Values

Prefixing a target value with += or -=, like {left: '+=50px'}, animates a property relative to its current value instead of to an absolute one, which is useful for nudging an element by a fixed amount regardless of its starting position.

Example: Relative Values

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div id="box" style="position:relative;left:0px">Box</div>
    <script>
      $("#box").animate({left: "+=50px"});
    </script>
  </body>
</html>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.