-1

I need to add a class to a 'div' on click, for CSS3 animations. But I also require to have that class removed after the animation is over.

I tried something like this but it does not work -

$('.class').click(function() {
    $('.class').removeClass("animate");
    $(this).addClass("animate");
});

Please help, thanks.

Addicted
  • 149
  • 1
  • 3
  • 9

2 Answers2

3

You have two immediate possibilites:

1) Use a setTimeout function that fires after the animation is complete. To achieve this you should know how long the animation duration is:

$('.class').click(function() {
    var animDuration = 1000; //ms of the animation duration
    $(this).addClass("animate");
    setTimeout(function(){
       $(this).removeClass("animate");
    }, animDuration);
});

2) A better solution is to add an eventListener on animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd that fires whenever the animation is actually complete. For this approach you do not need to know the duration of the animation.

EDIT: from adeneo and also some code taken from here:

$('.class').click(function() {
    var animDuration = 1000; //ms of the animation duration
    $(this).addClass("animate");
    $(this).bind('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function () {
       $(this).removeClass('animate');
    });
});

The above code does almost what you say, "gets the duration dynamically". What it really does is listening for an event that fires when the animation is complete / finished. The reason for the multiple event listeners is because of browser compatibility, each browser fires its own event. (oAnimationEnd = Opera, MSAnimationEnd = IE etc)

Thanks: https://coderwall.com/p/hn7gsg

Community
  • 1
  • 1
subZero
  • 5,056
  • 6
  • 31
  • 51
  • That was quick thanks! I will test it out. Between is there any way to get the animation duration dynamically? I guess I will have to use html5 'data-' attributes, right? But will it work with multiple buttons? Can you provide the code? – Addicted Oct 21 '13 at 10:49
0

You can use animate function for animation

   $('.class').click(function() { 
        $(this).addClass("animate");
        $('.class').animate($('.class').removeClass("animate"),2000);   
    });
S. S. Rawat
  • 5,943
  • 4
  • 43
  • 59