Creating a bouncing div animation can add an exciting and dynamic element to your website or project. In this article, we will guide you through the steps to create this engaging effect using HTML, CSS, and a sprinkle of JavaScript.
First, let's create the HTML structure for our bouncing div. Open your preferred text editor and create a new HTML file. Inside the file, add the following code:
<title>Bouncing Div Animation</title>
<div class="bouncing-div"></div>
Next, let's move on to the CSS part. Create a new file named "styles.css" in the same directory as your HTML file. Add the following CSS code to style our bouncing div:
.bouncing-div {
width: 100px;
height: 100px;
background-color: #3498db;
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
border-radius: 50%;
animation: bounce 1s infinite alternate;
}
@keyframes bounce {
0% {
top: 0;
}
50% {
top: 200px;
}
100% {
top: 0;
}
}
Now, let's add some interactivity using JavaScript to make our div bounce. Create a new file named "script.js" in the same directory as your other files and insert the following JavaScript code:
const bouncingDiv = document.querySelector('.bouncing-div');
bouncingDiv.addEventListener('mouseover', function() {
bouncingDiv.style.animation = 'bounce 1s infinite alternate';
});
bouncingDiv.addEventListener('mouseleave', function() {
bouncingDiv.style.animation = 'none';
});
Finally, save all your files and open the HTML file in a web browser. You should see a bouncing div that moves up and down smoothly. Hover your mouse over the div to activate the animation and see it bounce dynamically.
Customize the width, height, colors, and animation duration to match your design preferences. Experiment with different keyframe percentages to adjust the bounce speed and height according to your liking.
By following these simple steps, you can easily create a fun bouncing div animation on your website or project. Experiment with different styles and effects to make your design truly unique and engaging! Have fun coding and happy bouncing!