JavaScript animationiteration
Event: Triggered on Animation Iteration
The animationiteration
event in JavaScript is a crucial part of working with CSS animations. It fires each time a CSS animation completes one cycle and begins again, offering an opportunity to execute specific JavaScript code at each iteration. This event is particularly useful for creating complex animations, syncing animation cycles with other scripts, and managing repeated animation sequences. In this article, we will explore the animationiteration
event, including its syntax, usage, practical examples, and browser compatibility.
What is the animationiteration
Event?
The animationiteration
event is triggered when a CSS animation completes one full cycle as defined by its animation-iteration-count
property and starts over. This allows developers to synchronize JavaScript functions with the animation loop. Unlike animationstart
(which fires only once) or animationend
(which fires at the animationβs final completion if it’s not set to infinite), animationiteration
fires each time an animation repeats its cycle.
Purpose of the animationiteration
Event
The primary purpose of the animationiteration
event is to:
- Sync JavaScript with animation cycles: Execute code at the start of each animation loop.
- Create complex animations: Manage multiple animations based on their iteration count.
- Implement repeating animation effects: Modify the animation on each repetition.
- Track animation progress: Monitor the number of times an animation has looped.
Syntax
The animationiteration
event is attached to an HTML element using the following syntax:
element.addEventListener('animationiteration', function(event) {
// Code to be executed on each animation iteration
});
Where:
element
: The HTML element to which the animation is applied.addEventListener()
: The method used to attach the event listener.'animationiteration'
: The name of the event.function(event)
: The function to be executed when the event occurs. The event object provides additional information about the animation.
Event Properties
The animationiteration
event object provides properties that offer information about the animation that triggered the event:
Property | Type | Description |
---|---|---|
`animationName` | String | The name of the CSS animation that triggered the event, as defined in CSS using the `animation-name` property. |
`elapsedTime` | Number | The amount of time (in seconds) the animation has been running when the event was triggered. It gives the total time elapsed not the time spent in current iteration cycle. |
`target` | Object | The DOM element on which the animation is running. |
`type` | String | The type of event that occurred, in this case, `’animationiteration’`. |
`timeStamp` | Number | The time at which the event occurred (in milliseconds since the epoch). |
Note: You can access these properties within the event handler function. π€
Examples
Let’s explore how to use the animationiteration
event with practical examples. Each example includes the necessary HTML, CSS, and JavaScript code to illustrate different use cases.
Basic Usage
This example demonstrates how to listen for the animationiteration
event and log the animation name and elapsed time to the console on each animation loop:
<!DOCTYPE html>
<html>
<head>
<style>
.animated-box {
width: 100px;
height: 100px;
background-color: lightblue;
animation: moveBox 2s linear infinite;
}
@keyframes moveBox {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
</style>
</head>
<body>
<div id="box1" class="animated-box"></div>
<script>
const box1_element = document.getElementById('box1');
box1_element.addEventListener('animationiteration', function(event) {
console.log("Animation Iteration:", event.animationName);
console.log("Elapsed Time:", event.elapsedTime);
});
</script>
</body>
</html>
In this example, the animated-box
div will move from left to right and loop indefinitely. Each time the animation restarts, the animationiteration
event is fired and information about the event is printed to the console.
Modifying Elements on Iteration
This example shows how to modify the background color of an element each time an animation iteration completes.
<!DOCTYPE html>
<html>
<head>
<style>
.animated-circle {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: lightgreen;
animation: changeColor 1.5s linear infinite;
}
@keyframes changeColor {
from { background-color: lightgreen; }
to { background-color: lightcoral; }
}
</style>
</head>
<body>
<div id="circle1" class="animated-circle"></div>
<script>
const circle1_element = document.getElementById('circle1');
const colors = ["lightblue", "lightcoral", "lightgreen", "lightsalmon", "lightseagreen"];
let colorIndex = 0;
circle1_element.addEventListener('animationiteration', function() {
circle1_element.style.backgroundColor = colors[colorIndex];
colorIndex = (colorIndex + 1) % colors.length;
});
</script>
</body>
</html>
Here, the animated-circle
div will change its background color on each animation iteration. It cycles through the given color array and is updated on each loop.
Using Iteration Count
In this example, we will add iteration count information inside the animated element. This will show the number of times animation looped inside the element itself.
<!DOCTYPE html>
<html>
<head>
<style>
.animated-text {
width: 100px;
height: 100px;
background-color: lightyellow;
text-align: center;
line-height: 100px;
animation: growText 2s linear infinite;
}
@keyframes growText {
0% { font-size: 1em; }
50% { font-size: 1.5em; }
100% { font-size: 1em; }
}
</style>
</head>
<body>
<div id="text1" class="animated-text">0</div>
<script>
const text1_element = document.getElementById('text1');
let iterationCount1 = 0;
text1_element.addEventListener('animationiteration', function(event) {
iterationCount1++;
text1_element.textContent = iterationCount1;
});
</script>
</body>
</html>
In this example, the content inside the animated-text
element will update on every iteration to show the number of loops it has completed.
Synchronizing Multiple Animations
This example demonstrates how to sync a secondary animation using setTimeout
with the animation iteration cycle. This method can be used to start multiple animations in sync.
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
gap: 20px;
}
.animated-box2 {
width: 80px;
height: 80px;
background-color: lightcoral;
animation: moveBox2 1.5s linear infinite;
}
.animated-circle2 {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: lightskyblue;
}
@keyframes moveBox2 {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
</style>
</head>
<body>
<div class="container">
<div id="box2" class="animated-box2"></div>
<div id="circle2" class="animated-circle2"></div>
</div>
<script>
const box2_element = document.getElementById('box2');
const circle2_element = document.getElementById('circle2');
box2_element.addEventListener('animationiteration', function() {
setTimeout(() => {
circle2_element.style.animation = 'pulse 1s ease-in-out';
circle2_element.addEventListener('animationend', () => {
circle2_element.style.animation = '';
}, { once: true});
}, 0);
});
</script>
</body>
</html>
In this example, the circle will pulse each time the square completes its animation loop. This shows how to start a second animation using the loop of the first one.
Using Canvas with Animation Iteration
This example combines HTML Canvas and animation iteration events. In this example, a moving circle will redraw on each animation iteration creating a trail behind it.
<!DOCTYPE html>
<html>
<head>
<style>
#canvas1 {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas1" width="300" height="150"></canvas>
<script>
const canvas1_element = document.getElementById('canvas1');
const ctx1 = canvas1_element.getContext('2d');
let x1 = 20;
const radius1 = 15;
function drawCircle(x) {
ctx1.beginPath();
ctx1.arc(x, 75, radius1, 0, 2 * Math.PI);
ctx1.fillStyle = 'blue';
ctx1.fill();
}
function animateCanvas1() {
ctx1.clearRect(0, 0, canvas1_element.width, canvas1_element.height);
drawCircle(x1);
x1 += 10;
if(x1 > canvas1_element.width + radius1) {
x1 = -radius1;
}
requestAnimationFrame(animateCanvas1);
}
animateCanvas1();
canvas1_element.addEventListener('animationiteration', function() {
drawCircle(x1);
});
</script>
<style>
#canvas1 {
animation: canvasAnim 5s linear infinite;
}
@keyframes canvasAnim {
from { transform: translateX(0); }
to { transform: translateX(0); }
}
</style>
</body>
</html>
This example demonstrates how the animationiteration
event can be integrated with Canvas API for drawing and re-drawing the animation on each loop. Since the x position updates every frame, we are adding the drawing logic inside the animation iteration handler.
Browser Support
The animationiteration
event is widely supported in modern browsers, ensuring consistency across various platforms.
Browser | Version |
---|---|
Chrome | Any |
Safari | Any |
Firefox | Any |
Edge | Any |
Opera | Any |
Note: Ensure to test your code on all target browsers to confirm full compatibility. β
Conclusion
The animationiteration
event is a key tool for web developers when creating complex and synchronized CSS animations. It allows you to execute JavaScript code at the start of each animation loop, providing precise control over animations and enabling you to build more dynamic and engaging user interfaces. This guide has covered the essential aspects of the animationiteration
event, including its syntax, usage, and practical examples. Experiment with these techniques to fully harness the potential of animation in your projects.