How to replay css3 transform animation after some iterations by jQuery

I have this animation on my image:

<div class="image_for_sping">
    <img src="/anyimage.png">
</div>

Where the image has style attribute added by jQuery:

animation: spin360 0.1s linear 0s 20 forwards paused, spin360 0.25s linear 2s 8 forwards, spin360 0.5s linear 4s 4 forwards, spin360 1s linear 6s 2 forwards, spin90 2s linear 8s 1 forwards

Css for this animations:

@-moz-keyframes spin360 { 100% { -moz-transform: rotate(-360deg); } }
@-webkit-keyframes spin360 { 100% { -webkit-transform: rotate(-360deg); } }
@keyframes spin360 { 100% { transform:rotate(-360deg); } }
@-moz-keyframes spin90 { 100% { -moz-transform: rotate(-90deg); } }
@-webkit-keyframes spin90 { 100% { -webkit-transform: rotate(-90deg); } }
@keyframes spin90 { 100% { -webkit-transform: rotate(-90deg); transform:rotate(-90deg); } }

How I can play again this animation by jQuery without page reloading?

Try example: https://jsfiddle.net/rzqc2bsh/1/

Upvotes: 2

Views: 406

Answers (1)

Asons
Asons

Reputation: 87303

To replay an animation you need to toggle it on/off, so if you do like this, where you always remove it before adding it, and then use a setTimeout to force a redraw, or else it won't work.

$(document).ready(function() {
  $("#btn").click(function(e) {
    $('.box').css('animation', '');
    setTimeout(function() {
      $('.box').css('animation', 'spin360 0.1s linear 0s 20 forwards paused, spin360 0.25s linear 2s 8 forwards, spin360 0.5s linear 4s 4 forwards, spin360 1s linear 6s 2 forwards, spin90 2s linear 8s 1 forwards');
    }, 5)
  });
});
.box {
  width: 100px;
  height: 100px;
  background-color: red;
}

@-moz-keyframes spin360    { 100% { -moz-transform: rotate(-360deg); } }
@-webkit-keyframes spin360 { 100% { -webkit-transform: rotate(-360deg); } }
@keyframes spin360         { 100% { transform: rotate(-360deg); } }
@-moz-keyframes spin90     { 100% { -moz-transform: rotate(-90deg); } }
@-webkit-keyframes spin90  { 100% { -webkit-transform: rotate(-90deg); } }
@keyframes spin90          { 100% { transform: rotate(-90deg); } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="box"></div>
  <input type="submit" id="btn" value="spin" />
</body>

Upvotes: 1

Related Questions