How to add function/element action after animate function runs in javascript?

Viewed 43

I have tried searching on SO and google and cant seem to find a decent answer on this question. I want to remove the element that is being animated after the animation is complete. After the single iteration, it puts the element back where it started. It seems to understand when the animation ends, where to add that last bit? The code:


svg.animate([
  // keyframes
  { transform: 'scale(2.5)'}, 
  { left: '50px',top:'175px',transform: 'scale(1.0)' }
], { 
  // timing options
  duration: 600,
  iterations: 1,
    easing:'cubic-bezier(0.89, 0.41, 1, 0.95)'
})

What I want to add:

svg.remove()

Any ideas? thanks!

2 Answers

Use a promise:

Promise.all(
  svg.getAnimations().map(
    function(animation) {
      return animation.finished
    }
  )
).then(
  function() {
    return svg.remove()
  }
)

Look into animation events

Example: HTML:

<button>Hello</button>

CSS:

@keyframes example {
  from {background-color: red;}
  to {background-color: yellow;}
}

button {
  background-color: red;
  animation-name: example;
  animation-duration: 2s; 
}

JS:

const button = document.querySelector("button");
button.addEventListener("animationend", () => { button.remove(); });

demo

Related