JavaScript DOM animations
Basic animations using JavaScript in the DOM involve changing the properties of HTML elements over time to create visual effects such as movement, resizing, or fading. JavaScript can be used to control these animations by manipulating CSS properties or using the Web Animations API.
1. Using CSS Transitions with JavaScript
CSS transitions allow you to change property values smoothly over a specified duration. JavaScript can be used to trigger these transitions by adding or removing CSS classes or directly modifying inline styles.
Example: Using CSS Transitions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transitions Example</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: blue;
transition: all 0.5s ease; /* Smooth transition for all properties */
}
.expanded {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div id="box"></div>
<button id="toggleButton">Toggle Size</button>
<script>
const button = document.getElementById('toggleButton');
const box = document.getElementById('box');
button.addEventListener('click', function() {
box.classList.toggle('expanded');
});
</script>
</body>
</html>
In this example:
- CSS Transitions: The
transition
property specifies that changes towidth
,height
, andbackground-color
should be animated over 0.5 seconds. - JavaScript Trigger: The
classList.toggle('expanded')
method adds or removes theexpanded
class, which triggers the transition.
2. Using JavaScript for Manual Animation
JavaScript can also be used to manually control animations by updating CSS properties in a loop using setInterval
or requestAnimationFrame
.
Example: Using requestAnimationFrame
for Animation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Animation Example</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<button id="animateButton">Animate</button>
<script>
const button = document.getElementById('animateButton');
const box = document.getElementById('box');
button.addEventListener('click', function() {
let startTime = null;
const duration = 2000; // Duration of the animation in milliseconds
const startWidth = 100; // Initial width
const endWidth = 200; // Final width
function animate(time) {
if (!startTime) startTime = time;
const elapsed = time - startTime;
const progress = Math.min(elapsed / duration, 1); // Ensure progress is between 0 and 1
box.style.width = startWidth + (endWidth - startWidth) * progress + 'px';
box.style.height = startWidth + (endWidth - startWidth) * progress + 'px';
if (progress < 1) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
});
</script>
</body>
</html>
In this example:
requestAnimationFrame
: This method is used to create smooth animations by calling theanimate
function before the next repaint.- Animation Function: The
animate
function calculates the progress of the animation and updates the size of thebox
accordingly.
3. Using CSS Keyframe Animations with JavaScript
CSS keyframe animations provide a way to define animations with multiple stages. JavaScript can be used to control when these animations start, stop, or change.
Example: Triggering CSS Keyframe Animations
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Keyframe Animations Example</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
}
@keyframes move {
from {
transform: translateX(0);
}
to {
transform: translateX(300px);
}
}
.animate {
animation: move 2s forwards;
}
</style>
</head>
<body>
<div id="box"></div>
<button id="animateButton">Animate</button>
<script>
const button = document.getElementById('animateButton');
const box = document.getElementById('box');
button.addEventListener('click', function() {
box.classList.add('animate');
// Optional: Remove the class after animation ends to allow re-triggering
box.addEventListener('animationend', function() {
box.classList.remove('animate');
});
});
</script>
</body>
</html>
In this example:
- CSS Keyframes: The
@keyframes move
defines an animation that moves an element from its original position to 300 pixels to the right. - JavaScript Trigger: The
classList.add('animate')
method is used to start the animation, which is defined by the CSS keyframes.
Best Practices
- Use
requestAnimationFrame
for Smooth Animations: For smoother animations, preferrequestAnimationFrame
oversetInterval
orsetTimeout
. It synchronizes animations with the browser’s repaint cycles. - Combine CSS and JavaScript: Use CSS for defining complex animations and JavaScript for controlling when and how they run. This approach keeps your code organized and leverages the strengths of both technologies.
- Performance Considerations: Avoid animating properties that can trigger layout recalculations (e.g.,
width
,height
). Instead, animate properties liketransform
andopacity
for better performance. - Accessibility: Ensure that animations do not negatively affect accessibility. For example, provide options to disable animations for users who prefer reduced motion.