About Lesson
Custom Animations in jQuery
Learn how to create custom animations with the powerful .animate()
method in jQuery. This method allows you to animate CSS properties dynamically for engaging and interactive web elements.
1. .animate() Method
The .animate()
method performs custom animations by specifying CSS properties and their target values.
Syntax:
$(selector).animate(properties, duration, callback);
- properties: A map of CSS properties and their target values.
- duration: Time (in milliseconds) the animation will take.
- callback (optional): A function to execute after the animation completes
Example:
JavaScript
$("#animate").click(function () {
$("#box").animate({
left: "+=100px", // Move 100px to the right
opacity: 0.5, // Reduce opacity to 50%
}, 1000); // Animation duration: 1 second
});
Practical Example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Animations in jQuery</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: lightblue;
position: relative;
margin: 20px auto;
border: 2px solid darkblue;
}
#animate {
display: block;
margin: 10px auto;
padding: 10px 20px;
background-color: darkblue;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="animate">Animate Box</button>
<div id="box"></div>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
$("#animate").click(function () {
$("#box").animate({
left: "+=100px",
opacity: 0.5,
}, 1000);
});
});
</script>
</body>
</html>
Explanation of the Code
- CSS Properties Animated:
left: "+=100px"
: Moves the box 100 pixels to the right from its current position.opacity: 0.5
: Reduces the element’s opacity to 50%.
- Duration:
1000
milliseconds (1 second) specifies how long the animation should take.
- Event Listener:
- The animation starts when the button with ID
animate
is clicked.
- The animation starts when the button with ID