How do I run the animation every time I click the same button?

Asked

Viewed 43 times

0

<html>
<body>
<style>



#novo{
border:1px solid red;
width:375px;
height:467px;
background-image: url("file:///storage/emulated/0/download/inicialAnim.png");
animation: Anima 0.5s  steps(5) infinite;
transform:scale(0.6);
}
@keyframes Anima{
from{background-position:0px;}to{
background-position:-1875px;}

}
#btn1{
width:50px;
height:50px;
border:1px solid black;
border-radius:100px;
position:absolute;
left:563px;
bottom:50px;
background-color:#FF0900;
}

</style>
<div id = "novo"></div>
<div id = "btn1"></div>
<script>




var verify;
var anima = document.getElementById("novo");
var anim = document.getElementById("btn1");



anim.onclick = function play(){

anima.style.animationPlayState = "paused";
verify = true;
if(verify == true){
anim.addEventListener("click",verifica);

}

}

function verifica(){

anima.style.animationPlayState = "running";
anim.addEventListener("click",play);

}



</script>
</body>
</html>

  • Welcome Danilo, try to be clearer in what you want to do.

  • Okay, I’ll be more specific

  • 1

    Thanks André. I liked the site when I have doubts I will try to take here thanks man, thanks even.

1 answer

1

You can use a single function to do this by switching the variable value verify in true and false, using a if..else. In your code, the function play is anonymous and will not be called on .addEventListener. Behold:

var verify;
var anima = document.getElementById("novo");
var anim = document.getElementById("btn1");

verifica();
function verifica(){
   if(!verify){
      verify = true;
      anima.style.animationPlayState = "running";
   }else{
      verify = false;
      anima.style.animationPlayState = "paused";
   }
   anim.addEventListener("click", verifica);
}
#novo{
border:1px solid red;
width:375px;
height:467px;
background-image: url("https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg");
animation: Anima 0.5s  steps(5) infinite;
transform:scale(0.6);
}
@keyframes Anima{
from{background-position:0px;}to{
background-position:-1875px;}

}
#btn1{
width:50px;
height:50px;
border:1px solid black;
border-radius:100px;
position:absolute;
left:563px;
bottom:50px;
background-color:#FF0900;
}
<div id = "novo"></div>
<div id = "btn1">play/pause</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.