JavaScript AnimationEvent Object: Animation Events Explained
The AnimationEvent
object in JavaScript provides detailed information about CSS animation events that occur on HTML elements. These events include animation start, iteration, and end, allowing developers to trigger JavaScript functions to create interactive and dynamic web experiences. This guide covers the essentials of the AnimationEvent
object and provides practical examples to help you leverage animation events effectively.
What is the AnimationEvent Object?
The AnimationEvent
object is an event object dispatched when a CSS animation starts, repeats, or ends. It contains specific properties related to the animation, such as the animation name, the elapsed time, and the target element. By listening for these events, you can synchronize JavaScript code with CSS animations to perform actions at specific points in the animation lifecycle.
Purpose of the AnimationEvent Object
The primary purpose of the AnimationEvent
object is to:
- Provide notifications about the start, iteration, and end of CSS animations.
- Enable synchronization between CSS animations and JavaScript code.
- Allow dynamic modification of web page elements during animation events.
- Facilitate the creation of complex and interactive web animations.
Listening for Animation Events
To use the AnimationEvent
object, you need to listen for the corresponding animation events on the HTML element where the animation is applied. The three main animation events are:
animationstart
: Dispatched when the animation starts.animationiteration
: Dispatched when an animation repeats.animationend
: Dispatched when the animation finishes.
Syntax for Adding Event Listeners
You can add event listeners to an element using the addEventListener
method:
element.addEventListener(type, listener, options);
Where:
element
is the HTML element you want to listen to.type
is the animation event type (animationstart
,animationiteration
,animationend
).listener
is the function to be executed when the event occurs.options
(optional) is an object specifying characteristics about the event listener.
AnimationEvent Object Properties
The AnimationEvent
object includes the following properties:
Property | Type | Description |
---|---|---|
`animationName` | String | Returns the name of the animation that triggered the event. |
`elapsedTime` | Number | Returns the number of seconds an animation has been running when the event was triggered, excluding any time the animation was paused. |
`target` | Element | Returns the element the animation is running on. |
`type` | String | Returns the type of event being fired (e.g., “animationstart”, “animationiteration”, “animationend”). |
Basic Examples of Animation Events
Let’s explore basic examples of how to use animation events in JavaScript. Each example includes the necessary HTML and JavaScript code to demonstrate the usage of animationstart
, animationiteration
, and animationend
events.
Example 1: Responding to Animation Start
This example demonstrates how to listen for the animationstart
event and log a message to the console when the animation starts.
<div
id="animationStartDiv"
style="width: 100px; height: 100px; background-color: red; animation:
changeColor 2s linear;"
></div>
<style>
@keyframes changeColor {
0% {
background-color: red;
}
50% {
background-color: blue;
}
100% {
background-color: red;
}
}
</style>
<script>
const animationStartElement = document.getElementById("animationStartDiv");
animationStartElement.addEventListener("animationstart", (event) => {
console.log("Animation started: " + event.animationName);
});
</script>
Open your browser’s console to see the message when the animation starts.
Example 2: Responding to Animation Iteration
This example demonstrates how to listen for the animationiteration
event and log a message to the console when the animation repeats.
<div
id="animationIterationDiv"
style="width: 100px; height: 100px; background-color: green; animation:
rotate 2s linear infinite;"
></div>
<style>
@keyframes rotate {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
<script>
const animationIterationElement = document.getElementById(
"animationIterationDiv"
);
animationIterationElement.addEventListener("animationiteration", (event) => {
console.log("Animation iterated: " + event.animationName);
});
</script>
Open your browser’s console to see the message each time the animation repeats.
Example 3: Responding to Animation End
This example demonstrates how to listen for the animationend
event and log a message to the console when the animation finishes.
<div
id="animationEndDiv"
style="width: 100px; height: 100px; background-color: yellow; animation:
fadeOut 2s linear forwards;"
></div>
<style>
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
</style>
<script>
const animationEndElement = document.getElementById("animationEndDiv");
animationEndElement.addEventListener("animationend", (event) => {
console.log("Animation ended: " + event.animationName);
});
</script>
Open your browser’s console to see the message when the animation ends.
Example 4: Using Animation Properties
This example demonstrates how to use the animationName
and elapsedTime
properties of the AnimationEvent
object.
<div
id="animationPropertiesDiv"
style="width: 100px; height: 100px; background-color: orange; animation:
move 3s linear infinite;"
></div>
<style>
@keyframes move {
0% {
transform: translateX(0);
}
100% {
transform: translateX(200px);
}
}
</style>
<script>
const animationPropertiesElement = document.getElementById(
"animationPropertiesDiv"
);
animationPropertiesElement.addEventListener("animationiteration", (event) => {
console.log("Animation Name: " + event.animationName);
console.log("Elapsed Time: " + event.elapsedTime);
});
</script>
Open your browser’s console to see the animation name and elapsed time each time the animation repeats.
Advanced Techniques
Synchronizing JavaScript with CSS Animations
You can use animation events to synchronize JavaScript code with CSS animations. For example, you might want to trigger a function when an animation starts or ends to update the UI or perform other actions.
<div
id="syncAnimationDiv"
style="width: 100px; height: 100px; background-color: purple; animation:
pulse 2s ease-in-out infinite;"
></div>
<button id="syncButton">Start</button>
<style>
@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
</style>
<script>
const syncAnimationElement = document.getElementById("syncAnimationDiv");
const syncButtonElement = document.getElementById("syncButton");
syncAnimationElement.addEventListener("animationstart", (event) => {
syncButtonElement.textContent = "Animating";
});
syncAnimationElement.addEventListener("animationend", (event) => {
syncButtonElement.textContent = "Animation Ended";
});
</script>
In this example, the text of the button is updated when the animation starts and ends.
Dynamically Modifying Elements During Animation Events
You can also dynamically modify elements during animation events. For example, you might want to change the text or style of an element when an animation iterates.
<div
id="dynamicModifyDiv"
style="width: 100px; height: 100px; background-color: teal; animation:
slide 3s linear infinite;"
></div>
<style>
@keyframes slide {
from {
transform: translateX(0);
}
to {
transform: translateX(300px);
}
}
</style>
<script>
const dynamicModifyElement = document.getElementById("dynamicModifyDiv");
dynamicModifyElement.addEventListener("animationiteration", (event) => {
dynamicModifyElement.style.backgroundColor =
event.elapsedTime % 2 === 0 ? "teal" : "coral";
});
</script>
In this example, the background color of the div changes each time the animation iterates.
Real-World Applications of Animation Events
The AnimationEvent
object is used in various domains, including:
- Interactive Web Animations: Creating dynamic and interactive animations that respond to user actions.
- UI Transitions: Enhancing user interface transitions with synchronized JavaScript code.
- Game Development: Implementing game animations and effects.
- Data Visualization: Animating data visualizations to provide a more engaging user experience.
Use Case Example: Creating a Progress Bar
Let’s create a practical example that demonstrates how to use the AnimationEvent
object to build a progress bar. This example shows how to combine CSS animations and JavaScript to create a dynamic and visually appealing progress indicator.
<div id="progressBarContainer" style="width: 300px; height: 20px; border:
1px solid #ccc; overflow: hidden;">
<div
id="progressBar"
style="width: 0; height: 100%; background-color: #4CAF50; animation:
progress 5s linear forwards;"
></div>
</div>
<style>
@keyframes progress {
from {
width: 0;
}
to {
width: 100%;
}
}
</style>
<script>
const progressBarElement = document.getElementById("progressBar");
const progressBarContainerElement = document.getElementById(
"progressBarContainer"
);
progressBarElement.addEventListener("animationend", (event) => {
progressBarContainerElement.innerHTML = "Completed!";
progressBarContainerElement.style.textAlign = "center";
});
</script>
In this example, the progress bar fills up using a CSS animation, and when the animation ends, the text “Completed!” is displayed.
Browser Support
The AnimationEvent
object is supported by all modern web browsers, ensuring consistent behavior across different platforms.
| Browser | Version | Support |
| ————– | ——- | ———— |
| Chrome | Yes | All versions |
| Firefox | Yes | All versions |
| Safari | Yes | All versions |
| Edge | Yes | All versions |
| Opera | Yes | All versions |
| Internet Explorer | No | |
Conclusion
The AnimationEvent
object is a powerful tool for web developers, enabling the creation of dynamic and interactive web animations. By understanding how to listen for animation events and use the properties of the AnimationEvent
object, you can synchronize JavaScript code with CSS animations, dynamically modify elements, and create engaging user experiences. This guide provides you with the foundational knowledge and practical examples to start using animation events effectively in your projects. Happy animating!