CSS3 animate doesn’t play again on removeClass followed by addClass, but alters on toggleClass

If I do:

jQuery('#test').removeClass("change");
console.log(jQuery('#test').attr("class"));
jQuery('#test').addClass("change");

CSS3 animate bind to this class shows only first time.

.change {
  animation: redToTransparent 1s;
  animation-play-state: running;
  -webkit-animation: redToTransparent 1s;
  -webkit-animation-play-state: running;
}

Code in action : http://jsfiddle.net/adamovic/ato5akjx/

If you click on the button a few times, the animation doesn’t repeat. Why?

But it plays every second time, when using .toggleClass().

Browsers tested: Chrome, Firefox


solution

It looks like there has to be a delay between adding/remove classes.

Adding a delay of 100ms seems to work in Chrome/FF/IE.

Updated Example

$('#mybutton').on('click', function () {
  $('#test').removeClass("change");
  setTimeout(function () {
    $('#test').addClass("change");
  }, 100);
});

If you’re using jQueryUI, you could also use the following:

Example Here

$('#mybutton').on('click', function () {
  $('#test').removeClass("change").addClass("change", 100);
});