0

I am trying to get an animation to run whenever a button is clicked. Right now, it only runs if the page is refreshed and does not run again on repeated clicks of the button.

function myPlayFunction(el){  document.getElementById("myTest").style.animationPlayState = "running";
}   
#myTest {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;  
  animation-delay: 1s;
  animation-play-state: paused;
}

@keyframes example {
  0% {background-color: yellow;}
  50% {background: purple;}
  100%{background: red;}
}
<div id="myTest"></div>

<div><button onclick="myPlayFunction(this)" class="fas fa-play">&nbsp;&nbsp;Click this</button></div>
Honeybear65
  • 311
  • 1
  • 10

1 Answers1

3

As you can see in my example i detect with addEventListener the finish of animation then reset animation

const myTest = document.getElementById("myTest");
function myPlayFunction(el) {
  myTest.style.animationPlayState = "running";   
}
myTest.addEventListener("animationend", () =>{
  myTest.style.animation = 'none';
  myTest.offsetHeight;
  myTest.style.animation = null; 
}, false);
#myTest {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-delay: 1s;
  animation-play-state: paused;
}

@keyframes example {
  0% {
    background-color: yellow;
  }
  50% {
    background: purple;
  }
  100% {
    background: red;
  }
}
<div id="myTest"></div>
<div>
  <button onclick="myPlayFunction(this)" class="fas fa-play">&nbsp;&nbsp;Click this</button>
</div>
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34