Animation for Contact Forms

Here is the code snippet I am working with:

input[type=text], [type=email], select, textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type=submit]:hover {
  opacity: 0.9;
}


.contactform {
  position: relative;    
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px;
  z-index:2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom:auto;
  margin-top:1%;    
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;  
    
}
    
.contactform:hover { 
 animation-name: gradient;
 animation-duration: 15s;
 animation-iteration-count: infinite;    
       
}

.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto;    
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

@media screen and (max-width: 600px) {
  .column, input[type=submit] {
    width: auto;
    margin-top:0;
  }
}
 <section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="thankyou.html" method="POST">
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your firstname.." required>

            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your last name.." required>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>

            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate..." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

I am aiming to implement a shake effect when the user submits the form without entering any details.

Desired Outcome

Upon clicking submit with empty fields, I want the borders of the input boxes to turn red and shake. Only the placeholder boxes should exhibit this behavior, not the entire element. I tried using keyframes but couldn't achieve the desired result. Any recommendations would be greatly appreciated!

In simpler terms, I specifically want the first name, last name, email, and subject input box borders to turn red and shake.

Answer №1

Create a function that adds an event listener for the submit action. This function should loop through all the input and textarea fields, checking their validity using the checkValidity() method. If a field is invalid, its border color will be set to red using the borderColor style attribute, and it will animate with the animation style attribute.

To ensure the animation can play repeatedly, utilize the setTimeout function to reset the animation style attribute after a specified time interval.

document.querySelector('form').addEventListener('submit', function(e) {
  var isValid = true;
  this.querySelectorAll('input, textarea').forEach(function(f) {
    if (!f.checkValidity()) {
      isValid = false;
      f.style.borderColor = "red";
      f.style.animation = "shake 0.82s forwards";
      setTimeout(function(){f.style.animation="unset";},820);
    }else{
      f.style.borderColor = "initial";
      //Sets it back to normal if the field is valid
    }
  })
  if (!isValid) {
    e.preventDefault();
  }
})
input[type=text],
[type=email],
select,
textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #555;
  margin-top: 6px;
  margin-bottom: 16px;
  resize: vertical;
}

input[type=submit] {
  background-color: #0563bb;
  color: white;
  padding: 12px 20px;
  border: none;
  cursor: pointer;
}

input[type=submit]:hover {
  opacity: 0.9;
}
.contactform {
  position: relative;
  border-radius: 50px;
  background-color: #f2f2f2;
  padding: 5px; 
  z-index: 2;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: auto;
  margin-top: 1%; 
  width: 100%;
  animation-name: gradient;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}  
.contactform:hover { 
  animation-name: gradient;
  animation-duration: 15s;
  animation-iteration-count: infinite;
}  
.column {
  float: center;
  width: 50%;
  margin-top: 6px;
  padding: 20px;
  display: block;
  margin-left: auto;
  margin-right: auto; 
}    
.row:after {
  content: "";
  display: table;
  clear: both;
}      
@media screen and (max-width: 600px) {
  .column,
  input[type=submit] {
    width: auto;
    margin-top: 0;
  } 
}

@keyframes shake {
  10%, 90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%, 80% {
    transform: translate3d(2px, 0, 0);
  }
  30%, 50%, 70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%, 60% {
    transform: translate3d(4px, 0, 0);
  }
}
<section id="contact">
  <div class="container" data-aos="fade-up">
    <div class="contactform">
      <div style="text-align:center">
        <div class="section-title">
          <h2><br/>Get In Touch</h2>
        </div>
        <p>Feel Free To Reach Out To Me Through This Form! </p>
      </div>
      <div class="row">
        <div class="column">
          <form name="myform" action="thankyou.html" method="POST" novalidate>
            <label for="firstname">First Name</label>
            <input type="text" id="first name" name="firstname" placeholder="Your firstname.." required>

            <label for="lastname">Last Name</label>
            <input type="text" id="lastname" name="lastname" placeholder="Your last name.." required>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" placeholder="Your Email.." required>

            <label for="subject">Subject</label>
            <textarea id="subject" name="subject" placeholder="Lets Collaborate..." style="height:170px" required></textarea>
            <input type="submit" value="Submit">
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges and solutions in writing Protractor test cases

Recently delving into protractor e2e testing, I have developed my first test code. Seeking feedback and suggestions for improvement. describe("Map feedback Automation",function(){ it("Check if the Url works ",function() { browser.get(browser.params. ...

The behavior of placing an <a> element within an inline <li> element

I find the HTML / CSS result below to be quite puzzling and unexpected. I am eager to understand the reasoning behind how this is being interpreted. Consider: #nav { list-style-type-none } #nav li { display: inline; } /* make the LI's stack ho ...

How to Implement Flexbox Display Across Various Browsers Using jQuery?

Running into an issue here. I'm trying to switch from display: none to display: flex, display: flex-box, and display: -ms-flexbox but for some reason it's causing errors in my code.. Here's what I've been working on: $(elem).css({&apos ...

Node.js encountered an error: Address already in use. The specified port 8080 is currently being utilized by another application

My application was not functioning properly, and upon running the command "npm start", an error was thrown: Error: listen EADDRINUSE: address already in use :8080 Even after restarting my EC2 instance and attempting the command again, I encount ...

Overriding parent CSS styles with child elements results in an unrecognized property name

Is it possible to adjust the settings of a dropdown menu's parent using a child class in CSS? When attempting this, an "unknown property name" error is encountered on the child class, even though the same property is used within the parent class. The ...

Discovering what is impeding the rendering of a webpage

On a particular website, the server rendering happens quickly but there seems to be a delay on the client side which is causing the HTML to be rendered few seconds later. I suspect it could be due to some setTimeout function or similar; are there any tool ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

The type '(dispatch: Dispatch<any>, ownProps: OwnProps) => DispatchProps' does not match the parameter type 'DispatchProps'

Currently, I am working on a React application using Redux and TypeScript. I came across this insightful article that provided guidance on creating types for the mapStateToProps and mapDispatchToProps functions. Below is the code for my container: import ...

Using JQuery, calculate the quantity of "i" elements with the classes "fa" and "

$(function() { $(".rate i").css('cursor', 'pointer'); $(".rate i").click(function() { $(this).add($(this).prevAll("i")).removeClass("fa-star-o").addClass("fa-star"); $(this).nextAll("i").removeClass("fa-star").addClass("fa-s ...

How come the action doesn't trigger in my React/Redux application?

Currently, I am in the process of developing a small application that incorporates modals. Instead of relying on pre-made packages like react-modal, I have taken the initiative to build the modal functionality from scratch. 1) Defining a reducer located i ...

The issue I am encountering is that the keyboard controls in JavaScript are not causing the

One of the key elements in my code revolves around JavaScript functionality. I have implemented a feature where objects can be moved by pressing keys such as "down" or "right". However, there seems to be an issue where an object loaded from a .json file is ...

When using AngularJS filter, the comparator will evaluate to true and display the ng-repeat list even when the input

Recently, I stumbled upon this interesting example fiddle showcasing the use of a comparator parameter to filter exact matches: http://jsfiddle.net/api/post/library/pure/ The priority is supposed to be a number between 1-100, but due to inputting it as t ...

What is the best way to stop a Vue.js state using clearInterval()?

In my Vuex code, I currently have the following: export default new Vuex.Store({ state: { intervalVar: 0 }, mutations: { SET(state, {key, value}) { state[key] = value }, }, actions: { doSo ...

Retrieve information from hyperlinks and organize it into a structured format in a chart

Is there a way to extract href data from a website page and input it into a table using jQuery? I often have clients who need me to transfer links from their old sites to my CMS. If we can put these links into a spreadsheet format, it would make importing ...

What is the best choice for my CSS: creating a block or an element using BEM methodology

** According to the official BEM website ** Create a block: If a section of code can be reused and does not rely on other page components being implemented. Create an element: If a section of code cannot be used separately without the parent entity (the ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

`Open popup to make edits on the form`

I'm new to MVC and trying to grasp the best practices. Currently, I need some guidance as I'm stuck with a certain task. My situation involves an edit form where users can update a person's information and view their current contacts. These ...

Incorporating date formatting to the existing documents

The mongoose schema I have created is structured in the following way. mongoose.Schema({ "url": String, "translations": [ { "targetLang": String, "source": String, ...

Creating nested objects in Javascript involves adding an object inside another object

There are two objects that I have: obj1= { '201609': 52, '201610': 54, '201611': 56, metric: 'promotionsOut', careerLevelGroups: [ { '201609': 52, &a ...

Using livevalidation, the Validate.Custom function can either give a false or true return value

I'm currently using LiveValidation for form validation and attempting to validate a username with an ajax call. The issue I'm facing is that I always receive the message that the username is unavailable, regardless of its actual availability stat ...