0

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.

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

If you remove a class and add it again the animation won't play.

You could wrap the add "shake" class in a setTimeout function with a tiny delay and the animation will work.

$canvas.className = "";

setTimeout(function(){ 
  $canvas.className = "shake";
}, 50);

Also you could use the following:

$canvas.classList.remove("shake");
void $canvas.offsetWidth;
$canvas.classList.add("shake");

The $canvas.offsetWidth; will trigger a reflow.

You can read more about it here: https://css-tricks.com/restart-css-animation/

1 Comment

Thank you for this alternative solutions. I tested the setTimeout solution and it works. I don't want to trigger the reflow of my canvas element, but it's good to know that trick!
0

Adding the timeout with some delay worked. I have added the delay equal to animation-duration but adding any amount of delay will work.

$btn.addEventListener("click", function(e) {
  e.preventDefault();
  console.log("clicked");
  $canvas.className = 'shake';
  setTimeout(function(){ $canvas.className = '';  }, 500);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.