jQuery Methods: animate()

By: Dusty Arlia
Published on Tuesday, December 17, 2013, 07:47 AM
Last Updated on Saturday, July 11, 2015 at 9:02 PM
Total Updates: 8

The animate() jQuery method is used to create more advanced custom animations. The first argument to animate() is a required object. It usually specifies what css properties to animate and the target value to animate to (the end value). Only numeric properties can be animated (pixels are assumed). If the value is a string, you may specify units. The second optional argument sets other options for the animation, like the easing function, duration, when to queue the next chained method (the queue property), or setting the callback function.

Here's an example without the options object:

//Reduce the height of all elements
//with the "body_div" class to 0px

$(".body_div").animate({height: 0});

Here's an example WITH the options object:

//Reduce the height and width of all elements
//with the "body_div" class to 0px over the time 
//period of 600 ms

$(".body_div").animate({
    height: 0,
    width: 0
}, {
    duration: 600
});

If you would rather pass the duration (in milliseconds or preset stings: slow or fast), easing function (default is swing), and callback function (the complete property: a funtion that will be called when the when the animation is complete) as the 2nd, 3rd, and 4th arguments (instead of in an options object), you can do that.

The CSS properties listed in the first argument are properties of an object. These CSS properties have to have number values. These are the only kind of CSS properties that can be animated. The number value is assumed to be pixels. You can specify a different unit of measurement by using a string. You can also use the show, hide, and toggle strings. If an animation uses show, jQuery will call the show() method once the animation is complete. The same goes for hide (it will call the hide() method once the animation is complete). toggle performs a show or hide depending on the current value of the attribute.

It is also possible to increase or decrease the CSS value using "+=" or "-=" at the beginning of your string. This will increase or decrease the current value by the value specified. Here is an example:

$(".thumbnail_image").animate({
    width: "+=20px",
    height: "+=20px"
});

width and height are CSS property names. But when they are used in JavaScript/jQuery, they are using the JavaScript property name. JavaScript doesn't allow you to use hyphens in variable names (which are used as property names) unless the variable name is in quotes (to force it to be a string). For example:

$(".article_body").animate({
    "padding-left": "+=20px",
});

jQuery, like JavaScript, also accepts camelcase identifiers (paddingLeft) to help you avoid quoting the variables.

Comments:

Ad: