Event: Click then Animate

When a click event occurs the animation should fire. The magick works because a html animation class is added to an elelemt.

by Per Thykjaer Jensen

HTML

<h1>Animate after a Click Event</h1>
<p>User interaction: please click the yellow square and see what happens.</p>

<!-- here is the square for the animation -->
<div id="square"></div>

CSS

body {
  background-color: #000;
}
h1, p {color: #fff;}
#square {
  background-color: yellow;
  width: 125px;
  height: 125px;
}
@keyframes example {
  from {left: 0px;}
  to {left: 200px}
}
.animate {
  position: relative;
  animation-name: example;
  animation-duration: 4s;
}

JavaScript

// function that will fire after click


let runAnimation = function(){
  square.classList.add("animate");
  setTimeout(clearClass, 4000);
}

// element.addEventListener("click", myAddClassFunction);
square.addEventListener("click", runAnimation);

let clearClass = function(){
  square.classList.remove("animate");
}

// setTimeout(myFunction, 3000); 
//