Mark Wilson Mark Wilson - 27 days ago 16
CSS Question

Detect being animated and end of animation state for animate.css with jQuery

I am using animate.css to animate few blocks on my web page.

<a href="#" class="clicktoanimate">Click to animate</a>
<div class="div-to-animate">
some content...
</div>


$('.clicktoanimate').click(function(direction){
$('.div-to-animate').addClass('animated fadeIn');
});


So that does the animation.

But now I want to do some tasks when it is being animated and when the animation is done.

So, to check if it is being animated, I used the following condition

if ($('.div-to-animate').hasClass('animated')) {
// do something
}


which does fine but not for all cases. Because the animated class is not being removed after the transition.

So, I guess the only piece of puzzle I need to solve now is: How to remove the animated class after the animation is completed.

Answer

You can listen for the animationend event and remove the class when it fires:

$(".div-to-animate").on("animationend", function() {
    $(this).removeClass("animated");
});

Example:

$(".div-to-animate").on("animationend", function() {
  console.log("done");
  $(this).removeClass("animated");
}).addClass("animated fadeIn");
.animated {
  color: green;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/>
<div class="div-to-animate">This is the div, it's green while being animated</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments