Repeat animation by clicking button

Viewed 3477

I would like to repeat animation every time, when I click my button. I tried to do something like this.

const dist = document.querySelector('.dist');

document.querySelector('button').addEventListener('click', () => {
  dist.classList.remove('animation');
  dist.classList.add('animation');
});
.dist {
  width: 100px;
  height: 100px;
  background: black;
  margin-bottom: 30px;
}

.animation {
  transform: scale(1.5);
  transition: transform 3s;
}
<div class="dist"></div>
<button type="button">Trigger Animation</button>

But actually, this snippet does it only one time.

dist.classList.remove('animation');
dist.classList.add('animation');

Shouldn't this part remove state and start animating from the beginning?

4 Answers

I had The same issue and the above answers helped me get the solution that worked for me . the requestAnimationFrame() was adding the class before the animation is complete , and the setInterval() was keep executing for ever after user clicks and might conflict with the next clicks so , I had tow solutions either using requestAnimationFrame() with time stamp Or use setTimeout() and clearInterval() with the following steps :

  1. make a separate function for adding class
function addAnimation(){
 dist.classList.add('animation');
}
  1. Inside the removing animation function call the addAnimation() inside setTimeout() and assign that into variable so we can use clearInerval() to stop it
document.querySelector('button').addEventListener('click', () => {
  dist.classList.remove('animation');
  animate = setTimeout(addAnimation,2000)
});
  1. now lets go back to the addAnimation() function and add clearInerval() ,this will stop the extra execution that might cause issues.
function addAnimation(){
 dist.classList.add('animation');
clearInerval(animate);
}

this way when user clicks the class is removed and after the setTimeout time the class is added (just once ) since we used clearInerval() after adding the class NOTE : in my case I was first adding the class to animate and then removing it . Hope that is clear and help some one; its too late form the question publish date. All The best!

Related