Aritra Hazra Aritra Hazra - 6 months ago 14
Javascript Question

Detecting "animationend" event of a chained animation set

This is my CSS, in which, three keyframes are bound together to make a chain animation

#anim-div{
-webkit-animation-name : mpbar-anim-page1, mpbar-anim-page2, mpbar-anim-page3;
animation-name : mpbar-anim-page1, mpbar-anim-page2, mpbar-anim-page3;
-webkit-animation-delay : 0s, 0.7s, 1.4s;
animation-delay : 0s, 0.7s, 1.4s;
-webkit-animation-duration: 0.7s;
animation-duration : 0.7s;
}


Is it possible to detect animationend event of the whole set?

when I try, it detects animationend for each individual keyframes (ending up firing 3 events)

Answer

Assuming that the number of animations is unknown and the name of the final animation is also unknown, you could achieve this by using getComputedStyle to read the animations into an array. Then, when the animationend event fires, increment a variable and execute the code you wish when the value of that variable equals the length of the array, like so:

var div=document.querySelector("div"),
    style=window.getComputedStyle(div),
    animation=style.getPropertyValue("animation")||style.getPropertyValue("animation-name"),
    count=animation?animation.split(",").length:0,
    ended=0;
if(count)
  div.addEventListener("animationend",function(){
    ended++;
    if(ended===count){
      // Your code here
      console.log(ended+" animations completed.");
    }
  },0);
div{
  animation:x 1s ease-in-out,y 1s ease-in-out 1s,z 1s ease-in-out 2s;
  background:#000;
  height:50px;
  width:50px;
}
@keyframes x{to{transform:rotatex(180deg);}}
@keyframes y{to{transform:rotatey(180deg);}}
@keyframes z{to{transform:rotatez(180deg);}}
<div></div>