Repeat a CSS animation every time I click the button (with Javascript)

0

How do I repeat an animation every time I click on an element with javascript, I tried to do it but only works once (on the first click), after clicking, the animation is already in the HTML code (if I see it by inspecting element), so it's no use clicking again because it does not work.

I'm doing it this way:

variavel.onclick = function efeito() {
    this.style.animation = 'nomeAnimacao 1s linear';
   }
    
asked by anonymous 23.03.2018 / 03:21

2 answers

0

You can first put the animation with nothing:

this.style.animation = '';

And then reapply the animation. The detail is that it has to give a small time interval for the change to be interpreted. You can do this by re-applying the value inside a setTimeout . :

setTimeout(() => this.style.animation = 'nomeAnimacao 1s linear', 5);

See the example:

const botaoAnimar = document.getElementById("animar");
const caixa = document.querySelector(".caixa");

botaoAnimar.addEventListener("click", ()=> {
  caixa.style.animation = "";
  setTimeout(() => caixa.style.animation = "deslizar 1s linear", 5);
});
.caixa {
  background-color:lightGreen;
  width:100px;
  height:100px;
}

@keyframes deslizar{
  0%   { margin-left: 0px; }
  50%  { margin-left: 200px; }
  100% { margin-left: 0px; }
}
<div class="caixa"></div>
<button id="animar">Animar</button>
    
23.03.2018 / 04:01
0

You can set the property of animation to "none" and use setTimeout that will empty the property of animation to empty "" and then it will inherit the CSS property again. >

Example:

variavel = document.getElementById("butt");

variavel.onclick = function efeito() {
   var e = document.getElementById("div");
   e.style.animation = "none";
   setTimeout(function() {
      e.style.animation = "";
   }, 100);
}
div {
    width: 100px;
    height: 100px;
    background-color: red;
    animation: nomeAnimacao 4s linear;
}

@keyframes nomeAnimacao {
    0%   {background-color: red;}
    25%  {background-color: yellow;}
    50%  {background-color: blue;}
    100% {background-color: green;}
}
<div id="div"></div>
<br>
<button id="butt" type="button">Reiniciar</button>

Edit

When you hit "none" in an animation, it is automatically canceled, returning to its initial state. By emptying the style, it takes over the CSS style and restarts. See the image that the style accepts none :

Forotherstyles,suchaswidth,thebehaviorissimilarexceptthatwidthdoesnotacceptnone.Here'sanexample:

variavel = document.getElementById("dvd");

variavel.onclick = function efeito() {
   var e = document.getElementById("div");
   e.style.width = "100px";
   setTimeout(function() {
      e.style.width = "";
   }, 2000);
}
div{
   width: 300px;
   height: 50px;
   background: red;
}
<div id="div">Clique no botão e aguarde 2s</div>
<input type="button" value="ok" id="dvd">
    
23.03.2018 / 04:19