Custom function for animate.css causing problems

277 views Asked by At

I'm using the animate.css library for my project. I thought it would be easier to create a jQuery function that would do most of the work for me. Here is the function:

$(function () {    
    $.fn.extend({
        animateCss: function (animationName, callback) {
            var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
            this.addClass('animated ' + animationName).one(animationEnd, function () {
                $(this).removeClass('animated ' + animationName);
                if(callback){
                    callback();
                };
            });
        }
    });

});

It works, I can call it from jQuery objects. The problem is that when I pass in a callback function from one object, it gets called, but the same function from that object gets called again when ANOTHER object calls the function without passing in a callback.

I'm not quite sure how this can happen, I come from a Java background. Is there some way that this function can retain the callback variable passed in for other objects?

1

There are 1 answers

8
Nathaniel Flick On

Here's an example, I've used the bare minimum here, but the beauty of css3 is that it doesn't require javascript to run, just the browser to interpret it; hence css3 only works so far back.

All the animation documentation is here, and here's one simple example of bounce:

.title-large {
  font-size: 48px;
  }
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="bounce animated title-large">Animate me</div>

My guess is either you don't have access to the html or want to let different animations be added dynamically? Either way you can add any classes you want and remove them after the animation is complete, which is what I think they are doing on the github demo page link above. Hope this helps!