jQuery Animation Examples with Code
A simple jQuery animate example
In this post, I'm going to show you how easy it is to use jQuery to change a CSS property so you can add animation effects to your page.
For example, you can use jQuery animations to make something like this:
You'll learn about the options available for jQuery animation effects and how to animate multiple elements sequentially. You'll also learn how to animate backgroundColor and create a show/hide effect with jQuery. When you're finished with these examples, you'll know how to use jQuery to make great CSS animations.
Let's get started...
Quick Explanation
The animate() is a jQuery method that is used for changing CSS property of an Element with effects.
$(selector).animate( properties , duration, easing , complete)
An element/s that will have the animation effect
An object of CSS properties and values that the animation will move toward.
The time where the element will complete the animation.
Values: fast (200 ms), slow (600 ms) or any number in miliseconds.
Default: 400
The transition on how the animation will run.
Values:
swing or
linear Default:
swing
DIfference of
swing and
linear movement in graph
swing starts slowly and gradually increasing speed and slows down before it reaches the end of the duration
linear from start to end it moves with same speed
a function to execute after the animation is finished.
Default: fn(){}
Example Code
Here is an example where we animate an Element's width and sends a message when the animation is finished:
HTML <div id="changeMyWidth"></div>
CSS #changeMyWidth{
background: #ff000066;
width: 100px;
height: 100px;
margin-bottom:15px;
}
JS /*Changes Width on click*/
$('#btnAnimate').click(function(){
$('#changeMyWidth').animate(
{
width: '200px'
},
400,
"swing",
function(){
alert("Animation done!");
}
);
});
Tips
-
properties are not all css properties. Some properties must have a "Camel Case" style.
$('#elementId').animate({
background:'#fff'
},"slow");
The above code will not work
$('#elementId').animate({
backgroundColor:'#fff'
},"slow");
The above code will work. Which is equivalent to background-color:#fff in css.
The same will also be applied to other css properties like {marginTop:0px} , {borderColor:'#000'}
-
You can also chain animate() to execute another transition after the effect.
$('#changeMyWidth')
.animate(
{
width: '200px'
},
400,
"swing",
function(){
console.log("Width changed to 200px");
})
.animate(
{
width: '100px'
},
400,
"swing",
function(){
console.log("Width changed to 100px");
});
The above code will make #changeMyWidth's to 200px within 400ms and turns it back too 100px after it's done.
Replies (0)
Reply