heyseth
heyseth

Reputation: 27

addEventListener not firing when animation ends

I am using animate.css to animate an element. I would like to run some javascript when the animation finishes. For some reason, the following does not work.

myElement.addEventListener("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function() {
    //code never runs
}, false);

jQuery's .on() method works, but I would like to avoid using jQuery:

myElement.on("webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend", function() {
    //code runs
});

Why is this? And is there another way to detect when the animation finishes without using jQuery?

Upvotes: 2

Views: 1262

Answers (1)

zer00ne
zer00ne

Reputation: 43880

Put your multiple event types in an array the use .forEach() method.

SNIPPET

var div = document.querySelector('.animated');


['webkitAnimationEnd', 'animationend'].forEach(function(e) {
  div.addEventListener(e, eventHandler, false);
});

function eventHandler(e) {
  var tgt = e.target;
  tgt.style.color = 'red';
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">


<div class="animated tada">TADA!</div>

Upvotes: 1

Related Questions