The jQuery animate() method lets you create custom animations.
You can animate almost any CSS property, like width, height, or padding.
It is incredibly powerful for building unique interactive experiences.
The basic syntax looks like this: $(selector).animate({params}, speed, callback);
The required params define the CSS properties you want to animate to.
$("button").click(function(){
$("div").animate({left: '250px'});
});
Important Note: By default, HTML elements have a static position, meaning they cannot move. To animate elements physically, their CSS position property must be set to relative, fixed, or absolute!
You can animate multiple CSS properties at the same exact time.
Simply separate the properties with a comma inside the curly brackets.
Notice that CSS properties must be camel-cased when written in jQuery (e.g., paddingLeft instead of padding-left).
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
It is also possible to define relative values instead of absolute ones.
You achieve this by placing += or -= in front of the value.
This adds or subtracts from the element's current size or position.
$("button").click(function(){
// Adds 50px to the current height and width on each click
$("div").animate({
height: '+=50px',
width: '+=50px'
});
});
Almost all CSS properties with a numeric value can be animated.
However, you cannot animate non-numeric properties, like background-color.