27 Jan jQuery – Create Animations
To create Animations on a web page, use the jQuery animate() method. To move an element on a web page, you need to also use the position property. Set the value to relative, fixed, or absolute for the HTML element.
Let us see how to:
- Animate a div with animate()
- Animate a div with animate() – Use multiple properties
Animate a div
To animate a div, use the animate() method. In the below example, we have animated a div and moved it to the right. The left property is set to 300px and this is the limit till when the div will animate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").animate({left: '300px'}); }); }); </script> <style> div { background:red; border: 2px solid blue; height:200px; width:200px; color: white; text-align: center; font-size: 25px; position:absolute; } </style> </head> <body> <h1>jQuery Animation</h1> <button>Animate</button><br> <p>Click the above button to animate the below box:</p> <div>This box will get animated</div> </body> </html> |
Output
Animate a Div – Use multiple properties)
In this example, we will animate a Div and update the height, width, and font size as well. With jQuery, we can easily animate a div using the animate() method and update the div properties alongside. That means we can change multiple properties of that specific element.
Let us see an example wherein we will animate a div and update the height, width, and font size properties as well. For the animate() method, the font-size property is to be written in camel-case i.e. fontSize. This works for other properties as well:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div").animate({ left: '200px', height: '100px', width: '100px', fontSize: '15px' }); }); }); </script> <style> div { background:red; border: 2px solid blue; height:200px; width:200px; color: white; text-align: center; font-size: 22px; position:absolute; } </style> </head> <body> <h1>jQuery Animation</h1> <button>Animate</button><br> <p>Click the above button to animate the below box:</p> <div>This box will get animated and the properties will also change</div> </body> </html> |
Output
No Comments