search

Home  >  Q&A  >  body text

How to make a CSS animation run every time a subsequent class is added to an element

I have a CSS animation class set up so I can animate

elements.

When the input button is clicked, this class will be added to the

, I want the

to fly to the screen every time I click the input button in the example.

However, it only works the first time, any subsequent input clicks will not animate the element. What am I missing here?

$( document ).ready(function() {

jQuery('#cloc').click(function () {

jQuery('p').removeClass('anim').promise().done(function() {

jQuery('p').addClass('anim');

});



});


});
input {
margin-bottom:20px;
margin-top:50px;
}

p {
  opacity:1;
}

.anim {
  animation-duration: 200ms;
  animation-name: slidein;
}

@keyframes slidein {
  from {
  transform:translateX(-200px);
   opacity:0;
  }



  to {
    transform:translateX(0px);
    opacity:1;
    
  }
}

p {
position:absolute;
left:0px;
opacity:0;
animation-fill-mode: forwards;
animation-iteration-count: 1;

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position:relative">
<p>
HERE IS A TESTER FOR YOU.
</p>
</div>
<input type="button" id="cloc" value="test">

P粉714780768P粉714780768432 days ago536

reply all(1)I'll reply

  • P粉494151941

    P粉4941519412023-09-10 13:10:30

    You need to add a new event listener to the animationend event to reset the property
    animation-name to none

    Like the following code:

    $( document ).ready(function() {
    
          $('#cloc').click(function () {
    
            $('p').removeClass('anim').promise().done(function() {
    
              $('p').addClass('anim');
    
              setTimeout(function() {
                  $('p').removeClass('anim');
              },1000);
        
    
            });
    
          });
    
        });

    reply
    0
  • Cancelreply