Animationend eventlistener only fires once - why?

<!DOCTYPE html>
<html>
<head>
<style> 

div#blink {
  width: 100px;
  height: 100px;
  background-color: peru;
  position: relative;
  animation: example infinite;
  animation-duration: 1s;
}

@keyframes example {
  50% {background-color:tomato;}
}
</style>
</head>
<body>


<div id="blink"></div>
<p id="time">asdf</p>

</body>
<script>
var tar = document.getElementById("blink")
var sec = document.getElementById("time");
function blink() {
var dur = Math.random() * 2.5
tar.style.animationDuration = dur;
sec.innerText = dur
console.log("fired")
}

tar.addEventListener("animationend", blink())

/*. 
*/
</script>
</html>

Sorry about the inline HTML. Anyway, the animation loops, but the eventListener only fires once (“fired” only appears in the console once and the text doesn’t change.). How can I fix this?

I’ve tried animationiteration too, but it doesn’t work.

Logically, it should be never fired, as the animation repeats infinitely! But, it is called once. Why?

You can see that you’re calling blink when you’re adding it as listener. The proper way is,

tar.addEventListener("animationend", blink)
2 Likes

Instead, you should use animationiteration event. And, here

You’ve to add "s" after dur to make it valid CSS value.

1 Like

Thanks! I changed it to tar.style.animationDuration = ${dur}s`` so it actually works now.

1 Like