Home > Enterprise >  How can I get a Javascript CSS animation to run more than one time?
How can I get a Javascript CSS animation to run more than one time?

Time:01-22

I have some Javascript code that runs a CSS animation. It works fine, but I need to refresh the browser to get it to run again. How can I modify my code to get it to run every time the button is clicked?

Below is the code I used.

/*Javascript*/
document.getElementById('LogoContainer').addEventListener('click',function() {
var c = document.getElementsByClassName('logo-rec');
for (var i = 0; i < c.length; i  ) {
c[i].classList.add('logo-animate');
}
})

/*HTML*/    
<button id="LogoContainer">
<div ></div>
</button>

/*CSS*/    
.logo-animate {
animation-name: MoveLeft;
animation-duration: 3s;  
}
    
@keyframes MoveLeft {
0% { transform : translatex(0px) }
50%  { transform : translatex(-15px) }
100%  { transform : translatex(35px) }
}

CodePudding user response:

You can utilize the "animation-iteration-count" property in your CSS to specify the number of times that the animation should execute. For instance, to make the animation run indefinitely, you may set the animation-iteration-count to "infinite" as follows:

.logo-animate {
animation-name: MoveLeft;
animation-duration: 3s;  
animation-iteration-count: infinite;
}

Alternatively, you can specify a numerical value to denote the number of repetitions desired. Such as:

.logo-animate {
animation-name: MoveLeft;
animation-duration: 3s;  
animation-iteration-count: 5;
}

This will run the animation 5 times.

CodePudding user response:

The problem is that once the animation has run the system thinks - well I've run it, so it doesn't get run again when you click (the animation name stays the same).

So, this snippet adds an event listener for the animationend event and when that happens it removes the class setting that caused the animation so when you come to click again it's a new class setting and the animation happens once more.

document.getElementById('LogoContainer').addEventListener('click', function() {
  var c = document.getElementsByClassName('logo-rec');
  for (var i = 0; i < c.length; i  ) {
    c[i].classList.add('logo-animate');
    c[i].addEventListener('animationend', function() {
      this.classList.remove('logo-animate');
    });
  }
})
.logo-animate {
  animation-name: MoveLeft;
  animation-duration: 3s;
}

@keyframes MoveLeft {
  0% {
    transform: translatex(0px)
  }
  50% {
    transform: translatex(-15px)
  }
  100% {
    transform: translatex(35px)
  }
}
<button id="LogoContainer">
<div >abcd</div>
</button>

  • Related