Sara Ree
Sara Ree

Reputation: 3543

Detect the end of specific CSS animation of an element

We have two CSS animation keyframes that will be added or removed to the element using Javascript:

One for hiding the element by animating it from top to bottom:

upperGuideText.classList.add("upperGuideAnimeHide"); // Hide CSS KeyFrames

And another for showning the element by animating it from bottom to top:

upperGuideText.classList.add("upperGuideAnimeShow"); // Show CSS KeyFrames

Simply we add and remove them via classes to the element.

Then we create a function to handle these show and hide animations named guideReveal.

Each time we invoke guideReveal and pass a text to the function there will be two steps:

First, we hide the last text (animate it from top to bottom)

Then we add and animate the new text that is just passed to the function (animate it from bottom to top).

The code is simple, please have a look at it:

function guideReveal(text){

// Hide the `upperGuideText` on each guideReveal function execution
upperGuideText.classList.add("upperGuideAnimeHide"); // Hide CSS KeyFrames
upperGuideText.classList.remove("upperGuideAnimeShow"); // Show CSS KeyFrames

 // After a delay show another `upperGuideText`
  setTimeout(function(){
  upperGuideText.innerHTML = `${text}`;

  upperGuideText.classList.add("upperGuideAnimeShow"); // Show CSS KeyFrames
  upperGuideText.classList.remove("upperGuideAnimeHide"); // Hide CSS KeyFrames

  //Track end of only `upperGuideAnimeShow` animation! It's not working right now
  upperGuideText.addEventListener("webkitAnimationEnd", function(){
  console.log('Animation of guide ended..!')
  });

  }, 1000);
}

So far when the text shows up and when the text hides down we can track the end of the animation using webkitAnimationEnd but, I don't want to track the end of hide animation...

How can we Track the end of only upperGuideAnimeShow animation!

Upvotes: 1

Views: 1445

Answers (1)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

You could look for a specific animationName property of the animationend event, e.g.

let d = document.querySelector('div')
d.addEventListener('animationend', function(ev) {
   if (ev.animationName === 'fade') {
     alert('end')
   }
})
div {
   margin: 100px;
   width: 100px;
   height: 100px;
   background: yellowgreen;
   animation: fade 5s linear 0s 1,
              resize 2s linear 0s forwards;
   
}

@keyframes fade {
   from { opacity: 1 }
   to { opacity: 0 }
}

@keyframes resize {
   from { transform: scaleX(1) }
   to { transform: scaleX(2) }
}
<div></div>

in this example I've set two dfferent animations, but in the event handler I checked for the fade animation.

Upvotes: 4

Related Questions