DEV Community

Cover image for How to add shake animation on input:invalid
Stephen
Stephen

Posted on

How to add shake animation on input:invalid

In this short article we'll create a simple HTML with an input tag in a form tag and animate the input when user input is not valid.
This might seem a bit difficult and you may think you need Javascript to complete this task,but with only HTML and CSS(keyframes) we'll get this done.

Let's write some code

Adding our HTML

<!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
</head>
  <body>
     <form action="">
        <input type="text" minlength="5" />
      </form>
  </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Using the :invalid pseudo selector

In our css we style the input with the :invalid pseudo selector

<style>
input:invalid{
animation:shake .3s
}
</style>
Enter fullscreen mode Exit fullscreen mode

Adding shake animation with keyframes

Animations in CSS are mostly done with keyframes and so will our shake animation

<style>
.....
@keyframes shake{
25%{transform:translate(4px)}
50%{transform:translate(-4px)}
75%{transform:translate(4px)
}}
</style>
Enter fullscreen mode Exit fullscreen mode

Final Results

We set the minimum length of our input to 5, this means the input is invalid if the user enters less than 5 characters.
And the input box shakes when the user input is less than 5 , thus the form is invalid

Top comments (3)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
thecodingcrow profile image
thecodingcrow

neat! would have loved to see a video of the result 😄

Collapse
 
amiceli profile image
amiceli

Same, a video or a codepen will be cool ;)