The onanimationend
event in JavaScript is one of the events that occurs when a CSS animation comes to an end. With this event, handling this specific event in JavaScript can allow you to manage your own custom behaviors, such as the timing of animations, potential delays, or other significant actions that occur at the end of animations.
To start, we need to understand how onanimationend
works. When a CSS animation reaches its end, this event automatically triggers, and we can execute JavaScript code that follows this event. This is particularly useful when we want to perform actions immediately after the animation ends, such as removing DOM elements, adding or removing classes, or updating the content of the page.
Below is an example showing how to use onanimationend
:
<style>
.fade-out {
animation: fadeOut 2s;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
</style>
<div id="myElement" class="fade-out">This is a test element</div>
<script>
document.getElementById('myElement').addEventListener('animationend', function() {
this.style.display = 'none';
console.log('Animation has ended, the element is now hidden.');
});
</script>
Initially, we created a CSS style with an animation called fadeOut
that fades the element over 2 seconds to make it transparent so that it becomes hidden.
We have an element with the text "This is a test element" that has the class fade-out
, therefore, the animation will apply to it.
In the JavaScript section, we use addEventListener
to attach an event handler to the animationend
event. When the animation ends, the element becomes hidden, and a message is logged in the console.
This example simply shows how we can use the end of animations with onanimationend
to execute specific actions that may allow us to create interactive and engaging experiences on our web pages.