0

Is there a way to call the function animation multiple times after first click without changing the HTML code? I need to keep id and class as they are in the code. I was trying to use display property to none, but it doesn't seem to work. I want the animation to start when the <p> tag is clicked, but once I clicked it the first time, the animation doesn't start again. I'd like to call the function again even in the middle of the animation. I read all the other questions regarding this topic, but they don't seem to work for me, because the HTML was different. Please don't use Jquery, but you can use normal JS. Thank you!

     <!DOCTYPE html>
    <html>
   <head>
   <style>

 .something {
    background:blue;
    height:20px;
   width:20px;}
  .earth{
  position :relative;
    animation:move 10s linear;
  background:red;
  height:20px;
    width:20px;

         }
      @-webkit-keyframes move
     {
     from { left: 0%;  }
        to { left: 100%; }
      }

       </style>
      <script>
      function changetext (){

        document.getElementById("demo").style.color = "red";
      animation();
       }

        function animation(){
            document.getElementById('ghost').className ='earth';


        }
         function repeat(){
         var sd = document.getElementById("ghost").className ='earth';
        sd.style.display = 'none';
       }
     </script>
     </head>
       <body>
     <div class="something"></div>
      <div id="ghost"> </div>

      <p onclick="changetext();" id="demo"> HELLO WORLD </p>


     </body>
       </html>
0

1 Answer 1

0

You can remove the class and re-add it with a slight unnoticeable delay of 1ms.

function changetext() {
  document.getElementById("demo").style.color = "red";
  animation();
}

function animation() {
  document.getElementById('ghost').className = '';
  setTimeout(function(){
    document.getElementById('ghost').className = 'earth';
  }, 1);
}
.something {
  background: blue;
  height: 20px;
  width: 20px;
}

.earth {
  position: relative;
  animation: move 10s linear;
  background: red;
  height: 20px;
  width: 20px;
}

@-webkit-keyframes move {
  from {
    left: 0%;
  }
  to {
    left: 100%;
  }
<div class="something"></div>
<div id="ghost"> </div>

<p onclick="changetext();" id="demo"> HELLO WORLD </p>

Sign up to request clarification or add additional context in comments.

6 Comments

even with 0 instead of 1 it will work ;)
But 1 looks better there @TemaniAfif
why better ? :)
Looks better.. :P
@TemaniAfif and void just to nitpick, but the minimum value for setTimeout is 4ms anyway. Also, you could avoid asynchronicity altogether by forcing a reflow (ghost.offsetWidth; would do).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.