Javascript detects animationend as if it was animationstart

I'm trying to trigger a function after an animation ends, but it triggers even before the animation starts. I don't know what can be wrong. I've checked my code multiple times and even made a simpler one, which is the one I'm showing here.

I have an element animated through CSS, and another hidden through CSS:

<div class= "container">
  <div id="animated" style="background-color: lime; animation: changeColour 5s;">CONTENT</div>
  <div id="hidden" style="visibility: hidden;">CONTENT</div>
</div>

Then, I have Javascript set an event listener to change the "hidden" visibility property to "visible"

var elementHidden = document.getElementById("hidden")
var elementAnimated = document.getElementById("animated")
elementAnimated.addEventListener("animationend", afterAnimation());

function afterAnimation() {
  elementHidden.style.visibility = "visible";
}

And this is my animation:

@keyframes changeColour {
  0% {background-color: lime}
  50% {background-color: aqua}
  100% {background-color: lime}
}

Upvotes: 0

Views: 45

Answers (1)

zero298
zero298

Reputation: 26877

You are imediately causing afterAnimation to run because you are calling it using: afterAnimation().

Event listeners want references to functions.

In other words:

// Not this
elementAnimated.addEventListener("animationend", afterAnimation());

// This
elementAnimated.addEventListener("animationend", afterAnimation /* without () */);

The way you have it written right now, afterAnimation immediately changes visibility and then implicitly returns undefined. You are basically writing:

afterAnimation();
elementAnimated.addEventListener("animationend", undefined);

Upvotes: 4

Related Questions