With CSS, it’s easy to create animations using transitions and keyframes. Unfortunately there is no way in CSS to add a callback for animation events. With JavaScript, it possible to detect the events (start, restart and end) of CSS animations. This is useful if want to perform some actions based on the animation state.
Create an animation
Add HTML Markup
<div id="msElem"></div>
<button onclick="msStartAnim(this);">Start / Stop</button>
<p id="msAnimMsg"></p>
Add CSS
msElem{
height:70px;
width:70px;
background-color:green;
border-radius:50%;
margin:10px;
}
.msAnim{
animation: msAnimation 3s 2;
}
@keyframes msAnimation{
to{border-radius: 0%; background-color: red;}
}
Add JavaScript
To detect the animation events, we need to add the following animation event listeners to the element.
- animationstart – Occurs when the animation starts.
- animationend – Occurs when the animation ends.
- animationiteration – Occurs when an animation occurs again (repeated).
var msElem=document.getElementById('msElem');
var msMsg=document.getElementById('msAnimMsg');
//Adding Event listeners
msElem.addEventListener('animationstart',msAnimateStarted);
msElem.addEventListener('animationend',msAnimationEnd);
msElem.addEventListener('animationiteration',msAnimationIteration);
//This functionstarts or stops the animation on button click
function msStartAnim(tElem)
{
msElem.classList.toggle('msAnim');
msMsg.innerHTML="";
}
//Fired when animation starts
function msAnimateStarted()
{
msMsg.innerHTML+="Started";
}
//Fired when animation ends
function msAnimationEnd()
{
msMsg.innerHTML+=" End";
msElem.classList.remove('msAnim');
}
//Fired when animation is repeated
function msAnimationIteration()
{
msMsg.innerHTML+=" Restarted";
}
Try it yourself
See the Pen Detect animation start and end using JavaScript by Mishel Shaji (@mishelshaji) on CodePen.
Subscribe
Join the newsletter to get the latest updates.