Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

css

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

like image 445
Mladen Adamovic Avatar asked Feb 16 '15 19:02

Mladen Adamovic


2 Answers

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);
});
like image 95
Josh Crozier Avatar answered Oct 06 '22 19:10

Josh Crozier


Yes, looks like a timing issue. css-tricks has the solution: reload the element on the page. http://css-tricks.com/restart-css-animation/

Since I hate to work with timers and delays, it would look something like this:

jQuery('#mybutton').click(function() {

   newone = jQuery('#test').clone(true);
   jQuery('#test').remove();
   jQuery('.container').append(newone);

   newone.addClass('change');

 });
like image 26
rop Avatar answered Oct 06 '22 17:10

rop