In the previous examples, we have discussed different types of JQuery Animation techniques like fadeIn, fadeOut and sliders in JQuery. These are all predefined functions to animate the elements.
If we want to create our own custom animations, Jquery given us a method called animate(). The animate() is a function used to make a custom animation.
Syntax :
$(selector).animate({params},speed,callback);
Here, speed and callback are optional parameters. And {params} is a mandatory parameter is used to change the properties of an element(s).
The parameter speed represents three speeds. They are fast, slow and normal. It runs in few milliseconds. Callback represents the execution of function after animation completes. It executes only once for each element on a web page.
Points to Note using JQuery animation() :
- To animate a particular html element, initially that element should be in a position to move. To make that happen we should set the html element with the position: absolute, relative or fixed. By default all html elements are static position that means which doesn’t move.
- We can manipulate all css properties using animation() function; the only thing we need to remember is we should use the css property names as camelCase type. For instance if we want to use the margin-right property in animation() function, we should use this like marginRight instead of margin-right.
- We can manipulate the multiple css properties at a same time.
- We can also use the dynamic values to assign the properties. That means, we can assign width property like this : width : +=500; it means width = width+500.
- We can define multiple animate() statements line by line; if we do like that JQuery internally maintain a Queue and put all animations in that queue and it will execute like first in first out pattern. This process is also called as JQuery Queuing.
Here is the simple example in JQuery animation :
JQuery Animation Example :
[html]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>animate demo</title>
<style>
div {
position: absolute;
background-color: #027d3a;
left: 50px;
width: 90px;
height: 90px;
margin: 5px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="left">«</button>
<button id="right">»</button>
<div class="block"></div>
<script>
$("#right").click(function() {
$(".block").animate({
"left" : "+=50px"
}, "slow");
});
$("#left").click(function() {
$(".block").animate({
"left" : "-=50px"
}, "slow");
});
</script>
</body>
</html>
[/html]
Happy Learning 🙂