DOM Animations
DOM animations allow you to create interactive visual effects by dynamically changing the styles of elements using JavaScript. These animations can be achieved using CSS transitions, CSS animations, or JavaScript logic for fine control.
Key Topics
CSS Transitions
CSS transitions allow smooth changes between style states. Use the transition
property to define the duration and properties to animate.
<style>
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: background-color 0.5s ease;
}
.box:hover {
background-color: red;
}
</style>
<div class="box"></div>
Output
(The box changes color smoothly when hovered.)
Explanation: The transition
property defines the duration and timing function for the color change when the element is hovered.
CSS Animations
CSS animations allow you to create keyframe-based animations, defining the start and end points as well as intermediate states.
<style>
@keyframes move {
0% { transform: translateX(0); }
100% { transform: translateX(200px); }
}
.box {
width: 100px;
height: 100px;
background-color: green;
animation: move 2s ease-in-out infinite alternate;
}
</style>
<div class="box"></div>
Output
(The box moves back and forth horizontally.)
Explanation: The @keyframes
rule defines the animation sequence, and the animation
property applies it to the element.
JavaScript-Based Animations
JavaScript-based animations provide more control by using functions like setInterval
or requestAnimationFrame
to update styles dynamically.
let pos = 0;
const box = document.getElementById("animate");
function move() {
pos += 2;
box.style.transform = `translateX(${pos}px)`;
if (pos < 200) {
requestAnimationFrame(move);
}
}
move();
Output
(The element moves smoothly across the screen.)
Explanation: The requestAnimationFrame
function creates smooth animations by updating styles frame-by-frame.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating how JavaScript animations can be implemented dynamically.
<!DOCTYPE html>
<html>
<head>
<style>
#animate {
width: 50px;
height: 50px;
background-color: orange;
position: relative;
}
</style>
</head>
<body>
<div id="animate"></div>
<script>
let position = 0;
const element = document.getElementById("animate");
function animateElement() {
position += 1;
element.style.left = position + "px";
if (position < 300) {
requestAnimationFrame(animateElement);
}
}
animateElement();
</script>
</body>
</html>
Key Takeaways
- CSS Transitions: Smoothly transition between style states using the
transition
property. - CSS Animations: Create complex animations with
@keyframes
and theanimation
property. - JavaScript Animations: Use
requestAnimationFrame
for fine-grained control over animations. - Dynamic Animations: Combine JavaScript and CSS for responsive, interactive designs.