Şerban Şerban - 2 months ago 15
Javascript Question

Triggering a CSS animation again with a JavaScript event

I'm trying to trigger a CSS animation again with JavaScript. Tried a lot of tricks, nothing works.

Steps:


  1. <canvas class="shake">
    is added to
    document.body

  2. shake
    animation works!

  3. Press
    "Shake"
    button to re-add the CSS.

  4. Animation does not get triggered again.



Code

https://jsbin.com/pasitic/edit?css,js,console,output

The code is really simple. I'm hoping that there is a really simple and decent solution out there. I'm using vanilla JavaScript.

Update

Solved and the example was updated with the working code.

Answer

Try this:

...
$btn.addEventListener("click", function(e) {
  e.preventDefault();
  console.log("clicked");

  $canvas.className = "shake"; // Doesn't trigger the animation!
});

$canvas.addEventListener("animationend", function(e) {
  $canvas.className = "";
});

...

It adds an event listener that removes the class name which triggers after the animation ends.

Comments