Search code examples
javascriptjqueryformsvalidationdelay

jQuery - How to delay form submit until animation is finished?


I have this page animation which when the user leaves the page the document slides to the left. However, I also have this form which the user fills in then hits the "Next" button, and I want the submission of the form to wait until the animation is finished (animation e3ms?)

With my mediocre knowledge of JavaScript (especially forms and parsing) I wrote a script which to my knowledge should work, but it's not. Any ideas? Any help would be much appreciated.

JavaScript:

function ValidateForm() {
    var x = document.forms["myForm"]["myInput"].value;

    if(x == null || x == "") {
        $(".error-msg").animate({
            opacity: "1"
        });

        return false;
    } else {
        $("body").animate({
            "margin-left": "-200px",
            opacity: "0"
        });
    }
}

HTML:

<form name="myForm" action="next.html" onsubmit="return ValidateForm();">
    <input type="text" name="myInput" placeholder="Example: [email protected]">
    <span class="error-msg">You must fill out required elements!</span>

    <input type="submit" value="Next">
</form>

CSS code just styles form and sets the .error-msg with an opacity of "0".

P.S.: I know JavaScript form validation is dangerous, but once I publish my site I will back it up with PHP or ASP validation on my server, alongside JavaScript validation.


Solution

  • I would probably move your ValidateForm callback onto the onclick of the submit button. Then in your callback call e.preventDefault() to stop the form submitting from the click bubbling through. After that, submit the form manually in the callback of the animation (http://api.jquery.com/animate/)

    HTML

    <form name="myForm" action="next.html">
        <input type="text" name="myInput" placeholder="Example: [email protected]">
        <span class="error-msg">You must fill out required elements!</span>
    
        <input type="submit" value="Next" onclick="ValidateForm();">
    </form>
    

    Javascript

    function ValidateForm() {
        // stop the form auto submitting
        e.preventDefault();
        var x = document.forms["myForm"]["myInput"].value;
    
        if(x == null || x == "") {
            $(".error-msg").animate({
                opacity: "1"
            });
    
            return false;
        } else {
            $("body").animate({
                "margin-left": "-200px",
                opacity: "0"
            },
            {
                 complete: function() { $("form[name='myForm']").submit(); }
            });
        }
    }