For animations done in CSS, one can add EventListeners that fire in the events of animationstart, animationiteration and animationend.
@keyframes jumping-dot {
0% { transform: 'translateY(0px)' }
50% { transform: 'translateY(-100px)' }
100% { transform: 'translateY(0px)' }
}
#dot {
animation: jumping-dot 1s ease-in-out 1;
position: relative;
width: 50px;
height: 50px;
left: 50%;
margin-left: -25px;
border-radius: 50%;
top: 100%;
margin-top: -50px;
background-color: red;
}
const animationElement = document.getElementById('dot')
animationElement.addEventListener('animationstart', function () {
console.log('Animation started')
})
animationElement.addEventListener('animationend', function () {
const animationEndTime = window.performance.now()
console.log('Animation ended')
})
animationElement.addEventListener('animationiteration', function () {
console.log('Animation iteration ended')
})
If the animation is created via JS instead of CSS however, the same EventListeners won't fire.
const animationHandler = animationElement.animate(
[
{ transform: 'translateY(0px)' },
{ transform: 'translateY(-100px)', easing: 'ease-out' },
{ transform: 'translateY(0px)', easing: 'ease-in' }
], {
duration: 1000,
iterations: 1
}
)
Any idea, how to attach these EventListeners correctly?