0

var x = document.getElementsByClassName("box");

// Code for Chrome, Safari and Opera

x.addEventListener("webkitAnimationEnd", function(){
  console.log("event has ended");
});

// Standard syntax

x.addEventListener("animationend", function(){
  console.log("event has ended");
});
.box {
  background: red;
  position: absolute;
  padding: 100px;
}

.box:hover {
    animation-name: rotate; 
    animation-duration: 2s; 
    animation-iteration-count: infinite;
    animation-timing-function: linear;
}

@keyframes rotate {
    from {transform: rotate(0deg);}
    to {transform: rotate(360deg);}
}
<html>
 
 <body>
 
 <div class="box">
 </div>

   
 </body>
</html>

I'm trying to use js with css animations, im trying to display a message in the console log that the animation has ended but it not appearing, it gives me this error: x.addEventListener is not a function here is my code:

stephjhonny
  • 227
  • 3
  • 9
  • 22
  • 1
    `getElement**s**ByClassName` returns `HTMLCollection` i.e. many element**s**. You need to iterate over it and add listeners to every element. – Yury Tarabanko Apr 05 '17 at 08:30
  • Also a dupe of [What do `querySelectorAll`, `getElementsByClassName` and other `getElementsBy*` methods return?](http://stackoverflow.com/q/10693845/4642212). – Sebastian Simon Apr 05 '17 at 08:32

1 Answers1

0

Youll have to iterate through all elements and bind the event to each when selecting using class.

var x = document.getElementsByClassName("box");
// Code for Chrome, Safari and Opera
for (var i = 0; i < x.length; i++) {

  x[i].addEventListener("webkitAnimationEnd", function() {
    console.log("event has ended");
  });

  // Standard syntax

  x[i].addEventListener("animationend", function() {
    console.log("event has ended");
  });

}
.box {
  background: red;
  position: absolute;
  padding: 100px;
}

.box:hover {
  animation-name: rotate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<html>

<body>

  <div class="box"></div>

</body>

</html>
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33