How to implement loader after form validation using JavaScript?

My idea is to show loader circle after clicking a form submit button, because it's take some time to redirect user to page which let you know that form is submitted successfully. But with my limited JavaScrip knowledge I can't figure it out how to start loader only if user have filed out all required fields. Is it possible using JavaScript?

Here is my HTML code:

 <form> <input type="text" required> <button type="submit" onclick="this.classList.toggle('button--loading')"> <span>Save</span> </button> </form> 

and CSS code:

.button { position: relative; padding: 8px 16px; background: #009579; border: none; outline: none; border-radius: 2px; cursor: pointer; } .button:active { background: #007a63; } .button__text { font: bold 20px "Quicksand", san-serif; color: #ffffff; transition: all 0.2s; } .button--loading .button__text { visibility: hidden; opacity: 0; } .button--loading::after { content: ""; position: absolute; width: 16px; height: 16px; top: 0; left: 0; right: 0; bottom: 0; margin: auto; border: 4px solid transparent; border-top-color: #ffffff; border-radius: 50%; animation: button-loading-spinner 1s ease infinite; } @keyframes button-loading-spinner { from { transform: rotate(0turn); } to { transform: rotate(1turn); } } 
1

2 Answers

You have to change your HTML slightly and also have to add this JS function:

<form onsubmit="return submitTheForm(this);"> <input type="text" required> <button type="submit"> <span>Save</span> </button> </form> <script> function submitTheForm(theForm){ const eButton = theForm.querySelector('button[type="submit"]'); eButton.classList.toggle('button--loading'); } </script> 

Only replace start and end animation

const form = document.getElementById('form'); const handleSubmit = (event) => { event.preventDefault(); const data = new FormData(form); const url = "your url here"; const options = { method: "POST", body: data } // start animation fetch(url, options) .finally(() => { // end animation }); } form.addEventListener('submit', handleSubmit); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like