Search code examples
javascriptjquerycssshake

Using jQuery to trigger CSS shake animation, works every OTHER time ... why?


I have a rather simple fiddle here: http://jsfiddle.net/7aotzqmL/2/ that is supposed to shake a div with CSS animation upon clicking a link. It works, but only every other time (every second time). I'm stumped - can anybody help?

Other answers I've looked at mentioned how when using onmouseover you also need to attach onmouseout... but this is just a click so I'm not sure that's relevant. I just want the div to shake on every click rather than every other.

jsFiddle: https://jsfiddle.net/7aotzqmL/2/

CSS code:

$(function() {
  $('a').click(function(ev) {
    $('div').toggleClass('shaker');
    ev.preventDefault();
  });
});
div.shaker {
  animation: shake 0.3s;
  /* When the animation is finished, start again */
  animation-iteration-count: 1; //single shake 
}

@keyframes shake {
  0% {
    transform: translate(1px, 1px) rotate(0deg);
  }
  10% {
    transform: translate(-1px, -2px) rotate(-1deg);
  }
  20% {
    transform: translate(-3px, 0px) rotate(1deg);
  }
  30% {
    transform: translate(3px, 2px) rotate(0deg);
  }
  40% {
    transform: translate(1px, -1px) rotate(1deg);
  }
  50% {
    transform: translate(-1px, 2px) rotate(-1deg);
  }
  60% {
    transform: translate(-3px, 1px) rotate(0deg);
  }
  70% {
    transform: translate(3px, 1px) rotate(-1deg);
  }
  80% {
    transform: translate(-1px, -1px) rotate(1deg);
  }
  90% {
    transform: translate(1px, 2px) rotate(0deg);
  }
  100% {
    transform: translate(1px, -2px) rotate(-1deg);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">asd</a>
<div>shake</div>


Solution

  • Try this will work

    $(function(){
        $('a').click(function(ev){
    
           $('div').addClass('shaker'); 
    
           setTimeout(function(){
    
           $('div').removeClass('shaker'); 
           },300);
            ev.preventDefault();
        });
    });
    

    Below code is removing class on even time click, and you animation working on adding class

    $('div').toggleClass('shaker');
    

    in above solution, div class will be removed after 0.3secs animation, it will add 'shaker' class every time you click and animation will happen