HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Animate

While fading and sliding methods are great for basic tasks, the animate() method gives you total creative freedom. It allows you to create custom animations for almost any numeric CSS property on your page.


The animate() Syntax

The animate() method follows a specific pattern where you define the target CSS properties in an object.

$(selector).animate({params}, speed, callback);
  • params: An object defining the CSS properties to be animated.
  • speed: Optional duration ("slow", "fast", or milliseconds).
  • callback: Optional function to run when animation is complete.

Examples of Basic Animations

To move or resize an element, simply define the final values you want:

$("button").click(function() {
    $("#box").animate({
        left: '250px',
        opacity: '0.5',
        height: '150px',
        width: '150px'
    });
});
Crucial Note: By default, HTML elements have a static position. To move them (using left, top, etc.), you must first set the CSS property position to relative, fixed, or absolute.

Using Relative Values

Sometimes you don't know the exact pixel value, but you want to change it **relative** to its current size. You can do this by adding += or -= before the value.

$("button").click(function() {
    $("#box").animate({
        left: '+=50px',
        width: '+=20px'
    });
});

Using Predefined Values

You can even use special strings like "show", "hide", or "toggle" as property values to create combined animation logic.

$("button").click(function() {
    $("#box").animate({
        height: 'toggle'
    });
});

What can you animate?

You can animate any CSS property that uses **numeric values**. Here are some common properties:

width height opacity padding margin fontSize top/left/right/bottom
Important: Property names must be **camelCased** in jQuery. For example, font-size becomes fontSize, and margin-left becomes marginLeft.

Queue Functionality

If you write multiple animate() calls one after another for the same element, jQuery creates an internal **queue**. It will finish the first animation before starting the second.

var box = $("#box");
box.animate({height: '300px', opacity: '0.4'}, "slow");
box.animate({width: '300px', opacity: '0.8'}, "slow");
box.animate({height: '100px', opacity: '0.4'}, "slow");
box.animate({width: '100px', opacity: '0.8'}, "slow");
Pro Tip: To animate **colors** (like background-color), you need to include the jQuery Color plugin or use CSS transitions, as core jQuery only handles numeric animations.

Key Points to Remember

  • The animate() method can change multiple properties at once.
  • Always use camelCase for CSS property names (e.g., `paddingLeft`).
  • Elements must have a non-static position to move using top/left.
  • Use += or -= for relative changes based on the current state.
  • Animations are queued automatically and run sequentially.