Home > Software design >  Timeout a submit animation with JavaScript
Timeout a submit animation with JavaScript

Time:01-31

i have a submit button and a JavaScript. On click the button changes the state from active to inactive and a spinner animation is shown. I want to add to the script a timeout function. The button shall stop the animation and go back in active state after 3000 ms and show the normal submit button again. Here is my code:

 <button type="submit"  value="submit" id="ajax-form-button">Submit</button>

$(document).ready(function() {
 $("#ajax-form").submit(function(e) {
   // disable button
   $('#ajax-form-button').prop("disabled", true);
   // add spinner to button
   $('#ajax-form-button').html(
   `<i ></i> Bitte warten...`
   );            
 });
}); 

CodePudding user response:

window.setTimeout() is what you are looking for.

$(document).ready(function() {
  $("#ajax-form").submit(function(e) {
    // disable button
    $('#ajax-form-button').prop("disabled", true);
    // add spinner to button
    $('#ajax-form-button').html(
      `<i ></i> Bitte warten...`
    );

    window.setTimeout(() => {
      $('#ajax-form-button').prop("disabled", false); //re-enable button
      $('#ajax-form-button').html("Submit"); // oder "Absenden"  
    }, 3000) // run that function after 3 s

  });
});
  •  Tags:  
  • Related