简体   繁体   中英

Animate.css issue with jQuery click event

I am trying to apply field validation on a form I'm building with jQuery. I am also using the animate.css to apply different animation classes.

Assume I have one email field, the user clicks submit and checks whether or not the email they entered was valid. If it wasn't, apply the shake animation to the input field.

The code I have so far:

$submit.click(function(event) {
  event.preventDefault();
  var email = $input.val();

  // This does not seem to ever fire.
  $input.removeClass('shake');

  if (!method.validateEmail(email) || $.trim(email) == '') {
    $input.addClass('shake');
    return;
  }

  $form.submit();
});

This works for the first time the user submits the form. However, any subsequent clicks do not reproduce the shake animation. I tried applying removeClass('shake') before it checks whether or not the email is valid but it doesn't seem to ever fire.

The other way I came up with is to set an interval of 2000ms to check whether or not the input field has a class of shake, and if so remove it, but this is buggy since the user could submit the form 300ms before the interval ends, resulting in the animation only lasting that remaining amount of time. The code for the interval is:

setInterval(function() {
  if ($input.hasClass('shake')) {
    $input.removeClass('shake');
  }
}, 2000);

The fiddle can be found at http://jsfiddle.net/9Zs9T/1/

Any idea how to have the form shake every single submission with invalid input? Thanks.

Your code

$submit.click(function(event) { //...

sends a click event to the $submit selection. Presumably, what you want to do is execute the function when the user clicks

$submit.on("click", function(event) { //...

Fire an event at the end of the animation to remove the class instead of within the click event.

$input.one('webkitAnimationEnd mozAnimationEnd 
    MSAnimationEnd oanimationend animationend', $(this).removeclass('shake'));

I have not tested but I think it will work.


edit

Okay I think it's fixed now. Try this.

$("#form-email").on('animationend webkitAnimationEnd oAnimationEnd',
   function(){$('#form-email').removeClass("shake");});

'one' would only fire once so I changed it to 'on'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM