Using Relative Values in jQuery animate()

This article explains how to animate CSS properties relative to their current values using jQuery's animate() method. By prefixing property values with += or -=, you can dynamically increment or decrement numeric styles without needing to manually calculate their current dimensions or positions.

To use relative values in jQuery's animate() method, wrap the operator and target value in quotation marks as a string. The syntax += adds the specified value to the element's current value, while -= subtracts it.

Basic Syntax and Example

Here is a common scenario where a <div> element moves 50 pixels to the right every time a button is clicked:

$("#moveButton").on("click", function() {
    $("#box").animate({
        left: "+=50px"
    }, 500);
});

In this example, if the current CSS left value of #box is 100px, the animation smoothly transitions it to 150px over 500 milliseconds. Clicking the button again will move it from 150px to 200px.

Combining Multiple Relative Properties

You can apply relative animations to multiple properties simultaneously. This is useful for scaling dimensions and moving elements at the same time:

$("#expandButton").on("click", function() {
    $("#box").animate({
        width: "+=30px",
        height: "+=30px",
        top: "-=15px",
        left: "-=15px"
    }, "fast");
});

Key Considerations

  1. Units are Required: Always provide a unit of measurement (such as px, em, or %) inside the string. If omitted, jQuery defaults to pixels, but explicitly declaring units avoids unexpected layout calculations.
  2. CSS Positioning: When animating position properties like top, bottom, left, or right, ensure the target element has its CSS position property set to relative, absolute, or fixed. By default, elements are static, which ignores these positional offset properties.
  3. Numeric Properties Only: Relative operators can only be used on CSS properties that accept numeric values. They cannot be used directly with non-numeric properties, such as background colors or display types.