Maven Maverick Maven Maverick - 7 months ago 8
HTML Question

CSS class working only once on validation

I have defined a CSS class which looks like this -


@-webkit-keyframes wiggle {
0% {-webkit-transform:rotate(2deg);}
50% {-webkit-transform:rotate(-2deg);}
100% {-webkit-transform:rotate(2deg);}
}

@-moz-keyframes wiggle {
0% {-moz-transform:rotate(2deg);}
50% {-moz-transform:rotate(-2deg);}
100% {-moz-transform:rotate(2deg);}
}

@keyframes wiggle {
0% {transform:rotate(2deg);}
50% {transform:rotate(-2deg);}
100% {transform:rotate(2deg);}
}

.doWiggle {
-webkit-animation: wiggle 0.2s;
-moz-animation: wiggle 0.2s;
}


In JavaScript, I have this function -


function validateOnSubmit() {

var isValid = true;

if (document.getElementById("password").value.length <= 5) {
isValid = false;
document.getElementById("alert").className = "doWiggle";
}

return isValid;

}


The
validateOnSubmit()
function is implemented in the form as
onsubmit="return validateOnSubmit()"


The problem is that, the wiggling effect happens for only one click of the
submit
button. The wiggling effect does not happen if I click the
submit
button the second time or consecutive times.

What am I doing wrong ?

Answer

The problem is that you're not removing the className after the animation has run. Here is a fiddle with the corrected behavior or removing the className: https://jsfiddle.net/4fqLhbjx/1/

Basically what I did was I added this to the if condition:

setTimeout(function(){
    document.getElementById("alert").className = document.getElementById("alert").className.replace('doWiggle', '');
}, 300);

I chose 300 to make sure the animation had time to finish cleanly.