Search code examples
javascriptjquerycssanimate.css

Animate.CSS Replay?


I have an animation using Animate.CSS that I would like to have replay if the user would like but what I have attempted does not work. Here is the code:

HTML:

    <div class="img-center">
       <img src="path.jpg" class="feature-image animated rotateInDownRight" />
    </div>
       <p class="textcenter">&nbsp;</p>
    <div class="img-center">
       <a href="#" id="replay">Replay</a>
    </div>

JS:

var $j = jQuery.noConflict();
$j("#replay").click(function() {
    $j('.feature-image').removeClass('animated rotateInDownRight').addClass('animated rotateInDownRight');
});

I do know the script itself works as I can see it happen in Firebug however that animation doesn't animate again. How do I achieve this with Animate.CSS?


Solution

  • This is just a guess but it appears that jQuery isn't "finished" removing the class before it adds it back in. I know this makes NO sense, but it's how JavaScript works. It can call the next function in the chain before all the stuff from the first one is finished. I poked around the code on Animate.CSS's site and saw that they use a timeout in their animation function. You might try the same. Here's their code:

    function testAnim(x) {
        $('#animateTest').removeClass().addClass(x);
        var wait = window.setTimeout( function(){
            $('#animateTest').removeClass()},
            1300
        );
    }
    

    What this is doing is exactly like what you are doing except that it waits for the animation to finish, then removes the classes. That way when the other class is added back in, it is truely "new" to the tag. Here is a slightly modified function:

    function testAnim(elementId, animClasses) {
        $(elementId).addClass(animClasses);
        var wait = window.setTimeout( function(){
            $(elementId).removeClass(animClasses)},
            1300
        );
    }
    

    Notice two things: First this code would allow you to change what element gets the animation. Second, you remove the classes you added after 1300 milliseconds. Still not 100% there, but it might get you further down the road.

    It should be noted that if there is already some animation classes on the object it might break this JS.