How to call an animation using the onclick - HTML + JS command

Asked

Viewed 160 times

-1

Good afternoon! I’m new to the language, I’m trying to solve a problem using the onclick command to call an animation. Turns out I can’t make onclick work at all, let alone start/stop animation. Follow my code for analysis:

<div class="resposta3">
    <div id="balao" onclick="voar()" onclick="stop()">
        <img src="images/ex3/balao.png" alt="">
    </div>

    <script type="text/javascript">
       var mexendo = document.getElementById('balao');
       function mexer() {
          mexendo.classList.toggle("voar");
       }
       function stop() {
          mexendo.classList.remove("voar");
       }
   </script>
</div>

Follow also the animation and css part:

.resposta3{
  border: solid black 3px;
  width: 800px;
  height: 600px;
  background-image: url(../images/ex3/fundo.png);
}

#balao{
  animation: voar 1s linear alternate infinite;
}

@keyframes voar {
  0%{
    margin-top: -50px;
  }

  100%{
    margin-top: 30px;
  }
}

If you can help me I would be very grateful. Thank you

  • The names of your methods are wrong. You are calling voar(), and in your javascript there is the mexer().

  • There are several problems in your code, you have two events onclick in the same HTML element, in one of them is calling a function fly(), but, in the script does not have this function!

  • Another problem mentioned by @Leandrade is that there are two events onclick in his div.

1 answer

0

Because you are learning the language your code has several errors, it should not contain two or more of the same event Javascript in an element Html as it did in the onclick and also the way you did in Css the animation is already inserted in the div and in the script vc is calling the animation itself and not a class:

var balao = document.getElementById('balao');
var mexer = false;           // variavel de controle de clique no botao

function action() {
  mexer = !mexer;            // nega o valor conforme o clique no botao
  
  if(mexer) balao.classList.toggle('voando');
  else balao.classList.remove('voando');
}
.resposta3 {
  border: solid black 3px;
  width: 400px;
  height: 200px;
  background-image: url(../images/ex3/fundo.png);
}

.voando {
  animation: voar 1s linear alternate infinite;
}

@keyframes voar {
  0% {
    margin-top: -50px;
  }
  100% {
    margin-top: 30px;
  }
}
<div class="resposta3">
  <div id="balao" onclick="action()">
    <img src="https://i.pinimg.com/originals/a1/a8/39/a1a839b45f78793f00eeeddb752b4fc9.jpg" width="200" height="200" alt="">
  </div>
</div>

Browser other questions tagged

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