Animationend eventlistener only fires once - why?

<!DOCTYPE html>

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

@keyframes example {
  50% {background-color:tomato;}

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

var tar = document.getElementById("blink")
var sec = document.getElementById("time");
function blink() {
var dur = Math.random() * 2.5 = dur;
sec.innerText = dur

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


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)

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 = ${dur}s`` so it actually works now.

1 Like