Creating Interactive CSS3 Background Animations with JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS3 Animation Example</title>
<style>
.initial-state {
background-color: #ff0000;
padding: 2rem;
color: white;
font-size: 1.3rem;
}
@keyframes gradientCycle {
0% { background-color: #ff0000; }
25% { background-color: #ffff00; }
50% { background-color: #0000ff; }
100% { background-color: #00ff00; }
}
@-moz-keyframes gradientCycle {
0% { background-color: #ff0000; }
25% { background-color: #ffff00; }
50% { background-color: #0000ff; }
100% { background-color: #00ff00; }
}
@-webkit-keyframes gradientCycle {
0% { background-color: #ff0000; }
25% { background-color: #ffff00; }
50% { background-color: #0000ff; }
100% { background-color: #00ff00; }
}
@-o-keyframes gradientCycle {
0% { background-color: #ff0000; }
25% { background-color: #ffff00; }
50% { background-color: #0000ff; }
100% { background-color: #00ff00; }
}
.animated-state {
animation: gradientCycle 5s;
-moz-animation: gradientCycle 5s;
-webkit-animation: gradientCycle 5s;
-o-animation: gradientCycle 5s;
padding: 2rem;
color: white;
font-size: 1.3rem;
}
</style>
</head>
<body>
<div class="initial-state" id="demoDiv">Hello, CSS3 Animations!</div>
<button type="button" id="animateBtn">Start Background Animation</button>
<script>
const animateButton = document.getElementById('animateBtn');
const demoElement = document.getElementById('demoDiv');
animateButton.addEventListener('click', () => {
console.log('Button clicked to start animation');
if (demoElement.classList.contains('initial-state')) {
demoElement.classList.remove('initial-state');
}
demoElement.classList.add('animated-state');
});
</script>
</body>
</html>
-
Define Animation Keyframes: Use
@keyframesto specify a sequnece of style changes over time. Keyframe percentages (0% = start, 100% = end) map to specific property values. Vendor prefixes ensure compatibility with older browsers like Firefox, Safari/Chrome, and Opera. -
Encapsulate Animation in CSS Class: Create a dedicated class that references the defined keyframe animation via the
animationproperty. Include vendor-prefixed versions of this property to maintain compatibility. -
Apply Animation Dynamically: Use JavaScript to listen for user interactions (e.g., button clicks) and manipulate the DOM element’s
classListto apply the animated state class, replacing the initial static style.