Search code examples
javascriptjqueryhidewaitslideup

JQuery wait until an element has hidden before continuing


My Jquery code is as follows:

if($('#LoginFormError').is(':visible'))$('#LoginFormError').slideUp();
//Check inputs and run ajax
if(CheckInput('#LoginUsername') && CheckInput('#LoginPassword')){
    $('#LoginSubmit').attr('disabled', true);
    $.ajax({
        (..ajax stuf..)
    });
}else{
    $('#LoginFormError').html("Please fill in everything.");
    $('#LoginFormError').slideDown();
}

For the purpose of this, CheckInput returns true if the field is filled in.

What I want to do is if then #LoginFormError is visible, for the script to hide the element and then run the check procedures. The issue is though that #LoginFormError may not be visible at all, so I can't put everything into the call back from the SlideUp function, although I don't think I can.


Solution

  • Since the callback will always be called (even if the element is already hidden) there's no need to check. Just put everything in the callback:

    $('#LoginFormError').slideUp(400, function{
            //Check inputs and run ajax
            if(CheckInput('#LoginUsername') && CheckInput('#LoginPassword')){
                $('#LoginSubmit').attr('disabled', true);
                $.ajax({
                    (..ajax stuf..)
                });
            }else{
                $('#LoginFormError').html("Please fill in everything.");
                $('#LoginFormError').slideDown();
            }
        }
    );