javascriptcssanimationconditional-statementscss-animations

A Javascript if statement for a keyframes in CSS?


I've been searching all over the internet but couldn't find an answer to this.

Basically, I want to make an if statement in javascript... Once a keyframes animation in CSS3 gets to 100%, do some action. I just don't know what syntax to use.

I really appreciate any help you can provide.

CSS3:

@keyframes progress-animation{
0%{
    width: 0%;
}

100%{
    width: 100%;
}
}

@keyframes loader {
0% {
  transform: rotate(0deg);
}

25% {
  transform: rotate(180deg);
}

50% {
  transform: rotate(180deg);
}

75% {
  transform: rotate(360deg);
}

100% {
  transform: rotate(360deg);
}

}

What I want to do (in words):

if (progress-animation == '100%')
    stop animation (loader)

Sorry if it's a quite simple answer; I'm a bit new to Javascript.


Solution

  • You can utilize animationend event.

    You can also add a condition using animationName parameter received from the event to only check for particular animations.

    Here's a demo:

    const element = document.querySelector('.progress')
    element.addEventListener("animationend", onAnimationComplete);
    
    function onAnimationComplete(e){
      if(e.animationName==='progress-animation'){
         console.log("progress-animation ended")
      }
    }
    .progress{
      background:red;
      padding:10px;
      width:100px;
      border:solid 1px black;
      border-radius:16px;
      animation: progress-animation linear 3s;
    }
    @keyframes progress-animation{
      0%{
      width:0px;
      }
      100%{
       width:100px;
     }
    }
    <div class='progress'>
    
    </div>