jQuery animate() Method
The animate() method changes the CSS properties of an element step by step, to make your own animation. The other effects, like fadeIn and slideUp, are made with it.
Syntax
$(selector).animate({properties}, speed, easing, callback)
- properties: an object with CSS properties and their end values.
- speed: milliseconds, or ‘slow’ and ‘fast’. Default is 400.
- easing: the speed curve,
'swing'(default) or'linear'. - callback: a function that runs at the end.
Example
<div id="box" style="width:100px; height:50px; opacity:1;">Box</div>
$('#box').animate({
width: '300px',
opacity: 0.5
}, 1000, function () {
console.log('Animation complete');
});
console.log($('#box').css('width'));
console.log($('#box').css('opacity'));
Console output
Animation complete
300px
0.5
In a browser the box grows slowly for one second. Here the result is shown immediately, because our test has the animations switched off.
Rules for animate()
- Use camelCase for property names:
marginLeft,fontSize,borderWidth. - Only numeric properties can be animated, like width, height, left, opacity and font size. Colors need a plugin (jQuery UI or jQuery Color).
- To move an element, its
positionmust be relative, absolute or fixed.
Relative values
Use += and -= to change from the current value.
<div id="box" style="width:100px;">Box</div>
$('#box').animate({ width: '+=50px' });
console.log($('#box').css('width'));
$('#box').animate({ width: '-=20px' });
console.log($('#box').css('width'));
Console output
150px
130px
Special values
<div id="a" style="height:40px;">Panel</div>
$('#a').animate({ height: 'toggle' });
console.log($('#a').css('display'));
$('#a').animate({ height: 'toggle' });
console.log($('#a').css('display'));
Console output
none
block
The special values are 'show', 'hide' and 'toggle'.
Queue of animations
If you call animate() many times on one element, the animations run one after the other. This is called the queue.
$('#box')
.animate({ left: '200px' }, 500)
.animate({ top: '100px' }, 500)
.animate({ left: '0px' }, 500)
.animate({ top: '0px' }, 500);
Stop and delay
.stop()stops the running animation..stop(true)also clears the queue, and.stop(true, true)jumps to the end..delay(1000)waits before the next animation in the queue..finish()finishes all the animations of the queue at once.
Note:
For simple moves and fades, CSS transitions and animations are faster, because the browser can run them on the graphics card. Use animate() when you need a callback, or to support old code. Next: Method Chaining and Callbacks.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |