So I have a piece of code. The purpose is to play a selected animation from Animate.css on click.
The code
$(".container>parent").click(function () {
$('.element').css({
'animation': 'fadeInUp .2s',
'-webkit-animation': 'fadeInUp .2s'
});
});
The problem
Animation runs, but only one time. 'Infinite' attribute causes chaos :P
What else could I do, to play that animation every single time someone click it?
Thanks for your time.
My HTML:
<span class="parent">
<img src="assets/myimage.png" class="filter-image">
<span class="element">Text</span>
</span>
I want to animate the text everytime I click it.
$(".container>parent").click(function() {
$('.element').css({
'animation': 'fadeInUp .2s',
'-webkit-animation': 'fadeInUp .2s'
});
setTimeout(function(){
$('.element').removeAttr('style');
},300);
});
The animation won't work the second time if you don't remove animation class after the current animation finishes.
But how to remove animation property after the animation finishes?
Here's a snippet:
var support = {};
support.animation = (function() {
var animationEnd = (function() {
var element = document.body || document.documentElement,
animEndEventNames = {
WebkitAnimation : 'webkitAnimationEnd',
MozAnimation : 'animationend',
OAnimation : 'oAnimationEnd oanimationend',
animation : 'animationend'
}, name;
for (name in animEndEventNames) {
if (element.style[name] !== undefined) return animEndEventNames[name];
}
}());
return animationEnd ? { end: animationEnd } : false;
})();
function animate(elem, cls, callback) {
var $elem = $(elem);
var onEndCallbackFn = function(ev) {
if (support.animation) {
$elem.removeClass(cls);
this.removeEventListener(support.animation.end, onEndCallbackFn);
}
if (callback && typeof callback === 'function') { callback.call(this, ev); }
};
if (support.animation) {
$elem.addClass(cls);
$elem[0].addEventListener(support.animation.end, onEndCallbackFn);
} else {
onEndCallbackFn();
}
}
usage is simple, just call animate function, like this:
animate($('.selector'), 'classWithAnimation', callbackFn);
In you case, you said you are using animate.css library:
$(".container>parent").click(function() {
animate($('.element'), 'animated fadeInUp', function() {
console.log('animation complete');
);
});
Live example: jsFiddle