Search code examples
jquerycsscss-animationsfade

Why does my jQuery/CSS animation only work on first click?


I'm attempting to make an element fade out and then fade in each time a link is clicked. I have the following code, for some strange reason it only works on first click. Demo: http://jsfiddle.net/aueLr8k0/3/

$("body").on('click', 'a', function () {
   $("div").removeClass('fade').addClass('fade');
})
.fade {
    animation: fadeinout .5s;
}

@keyframes fadeinout {
  0%,100% { opacity: 1; }
  50% { opacity: 0; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">Click this</a><br><br>
<div style="height:200px;width:200px;background:red"></div>


Solution

  • You could listen to animationend event and remove class on it

    $("body").on('click', 'a', function () {
       $("div").addClass('fade').one('animationend', function() {
       	 $(this).removeClass('fade');
       });
    })
    .fade {
        animation: fadeinout .5s;
    }
    
    @keyframes fadeinout {
      0%,100% { opacity: 1; }
      50% { opacity: 0; }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a href="#">Click this</a><br><br>
    <div style="height:200px;width:200px;background:red"></div>