How to Use Easing in jQuery Animations

This guide explains how to implement easing functions in jQuery animations to control the acceleration and deceleration of animated elements. You will learn how to use jQuery's built-in easing options, expand your options using external easing libraries, and write custom mathematical easing equations directly into the jQuery easing object.

Built-in Easing in jQuery

By default, jQuery includes only two easing methods: swing (the default, which speeds up slightly in the middle) and linear (which moves at a constant speed throughout).

You can apply an easing function using the basic .animate() syntax by passing the easing name as a string:

// Using linear easing
$("#box").animate(
  { left: "300px" },
  1000,
  "linear"
);

You can also pass easing within an options object:

$("#box").animate(
  { left: "300px" },
  {
    duration: 1000,
    easing: "swing",
    complete: function() {
      console.log("Animation complete");
    }
  }
);

Expanding Easing Options

To access advanced easing options such as easeInQuad, easeOutBounce, or easeInOutExpo, you must include either the jQuery UI library or the standalone jQuery Easing plugin in your HTML file alongside jQuery:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include jQuery Easing Plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script>

Once loaded, you can call any of the extended easing formulas by name:

$("#box").animate(
  { top: "200px" },
  800,
  "easeOutBounce"
);

Creating Custom Easing Functions

You can define your own easing curve by extending the jQuery.easing object. In modern versions of jQuery, the easing function takes one parameter, x, which represents the progress of the animation as a normalized value from 0 to 1. The function must return a calculated position, also typically between 0 and 1.

Here is how to create a cubic acceleration easing curve:

// Define custom easeInCubic function
$.easing.customCubic = function (x) {
  return x * x * x;
};

// Apply the custom easing
$("#box").animate(
  { width: "500px" },
  1200,
  "customCubic"
);

Applying Per-Property Easing

jQuery allows you to assign different easing functions to individual CSS properties within the same animation call using an array containing the target value and the easing function:

$("#box").animate({
  width: ["400px", "linear"],
  height: ["200px", "easeOutBounce"]
}, 1000);