Zac
Zac

Reputation: 121

How to reset a css animation class using jquery?

    $('#btn_color').on('click', function(){
    if($('h1').hasClass('bounceInUp')){

        $('h1').removeClass('bounceInUp');
        $('h1').addClass('tada');

    }else if($('h1').hasClass('tada')){

        $('h1').removeClass('tada');
        $('h1').addClass('tada');

    }
});

When I load my page, the 'bounceInUp' class is added to my h1. But I want to play a second animation on click by adding the 'tada' class.

The problem is the animation plays only for the first click. Is there a way to "reload" the animation when the 'tada' class is added again and again and again?

I'm using this to animate my text using this: http://daneden.github.io/animate.css/

Upvotes: 2

Views: 4365

Answers (3)

hossein naghneh
hossein naghneh

Reputation: 566

with this simple code you do it ( you must use .width() ):

$('h1').removeClass('tada');
$('h1').width();
$('h1').addClass('tada');

Upvotes: 1

n1k1ch
n1k1ch

Reputation: 2692

Edited

You can attach single listener of animationend event to remove animation classes when animation ends

$(document).on('click', '#btn_color', function (e) {
    $('h1').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function (e) {
        $('h1').removeClass('animated bounceInUp');
    });

    $('h1').removeClass('animated bounceInUp').addClass('animated bounceInUp');
});

Demo

Upvotes: 2

Jack
Jack

Reputation: 2771

You could jquery's setTimeout to remove the class once the animation finishes:

setTimeout(function() {
  $('h1').removeClass('tada');
}, 3000); // The length of your animation

Upvotes: 3

Related Questions