I am trying to add an animationend
event to an element, but the event doesn't get fired. What am I doing wrong, and how can I fix it?
var btn = document.getElementById('btn');
var elem = document.getElementById('elem');
var timeOutFunc;
btn.addEventListener('click', function() {
elem.classList.add('show');
clearTimeout(timeOutFunc);
timeOutFunc = setTimeout(function() {
elem.classList.remove('show')
}, 1000);
});
elem.addEventListener('animationend', function(e) {
console.log('animation ended');
});
#elem {
background-color: orange;
width: 100px;
height: 100px;
opacity: 0;
transition: opacity 500ms ease;
}
#elem.show {
opacity: 1;
transition: none;
}
<button id="btn">Press Me</button>
<div id="elem"></div>
The animationend event is fired when a CSS Animation has completed. If the animation aborts before reaching completion, such as if the element is removed from the DOM or the animation is removed from the element, the animationend event is not fired.
In JavaScript, we can call the callback function once the animation is done. But in CSS, there is no option to perform any action after the end of the transition/animation. Whenever the transition is finished, the transitionend event will be triggered. We can use this event to find the end of the transition.
There are two separate animating events.
When using the css transition
use transitionend
, and when using @keyframes/animation
, use animationend
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With