Jquery: addClass, removeClass: animation only works once: why?

When I use this:

$("#passwordConfig").removeClass('shake animated').addClass('shake animate');

This only works once.

I need to add some time to make it work as many times as I want!

$("#passwordConfig").removeClass('shake animated');
                    setTimeout(function() {
                        $("#passwordConfig").addClass('shake animated');
                    }, 50);

Any idea why?

CSS:

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

@-webkit-keyframes shake {
  0%, 100% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }

  10%, 30%, 50%, 70%, 90% {
    -webkit-transform: translate3d(-10px, 0, 0);
    transform: translate3d(-10px, 0, 0);
  }

  20%, 40%, 60%, 80% {
    -webkit-transform: translate3d(10px, 0, 0);
    transform: translate3d(10px, 0, 0);
  }
}

@keyframes shake {
  0%, 100% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }

  10%, 30%, 50%, 70%, 90% {
    -webkit-transform: translate3d(-10px, 0, 0);
    transform: translate3d(-10px, 0, 0);
  }

  20%, 40%, 60%, 80% {
    -webkit-transform: translate3d(10px, 0, 0);
    transform: translate3d(10px, 0, 0);
  }
}

.shake {
  -webkit-animation-name: shake;
  animation-name: shake;
}
+4
source share
1 answer

This is because removeClass and addClass happen so fast that the DOM does not allow them to catch up. You can do something like this if you really hate setTimeout:

$("#passwordConfig").removeClass('shake animated').delay(50).queue(
    function (next) {
        $(this).addClass('shake animated');
        next();
    }
);

http://jsfiddle.net/51dwhd2o/

Switching a class is also good, but it looks like it will only work on every call.

+4
source

Source: https://habr.com/ru/post/1612317/


All Articles