tags:

views:

377

answers:

3

For example, i'm using the beforeSend option in the $.ajax function. In the code sample below, the .html function will get executed while the fade out is taking place on the statement before. How could i stop this behavior?

 jQuery("#container").fadeOut("slow", function() {
     jQuery("#container").removeClass('error');
 });

 jQuery("#container").html("success").fadeIn("slow");

So what happens is that during the fade out, jquery will inject the html "success". I want it to happen after the animation is complete.

How should i go about it?

Thanks!

+4  A: 

Use the callback...

jQuery("#container").fadeOut("slow", function() {
  // At this point, animation is complete, and the element is invisible
  jQuery(this).removeClass("error").html("success").fadeIn("slow");
});
Josh Stodola
I am not sure if `$(this)` is going to work inside the callback. You may need to re-query.
Josh Stodola
@Josh Stodola - $(this) will in fact refer to #container, no need to re-query
karim79
But I would like for the content of the div to fade in with it. I want to be able to change classes and div content while the div is not visible. Know what I mean?
Jeff
You need to put your fade in into the callback for the fade out then.
Josh Stodola
A: 

I use the jQuery FxQueues plugin 2.0

RioTera
A: 

If you're using this in context with an ajax call, then I would expect the latter code to be part of your success callback on it, not inline with the fade of the container. This will make the container hidden before the call and only show it after the call has returned successfully. You may actually want to split it so that the fadeIn occurs on complete so that you can do it whether the call is successful or not.

jQuery.ajax({
   ...
   beforeSend: function() {
                   jQuery("#container").fadeOut("slow", function() {
                       jQuery("#container").removeClass('error'); }
                   });
               },
   success:    function(data) {
                   jQuery("#container").html("success").fadeIn("slow");
               }
   ...
});


jQuery.ajax({
   ...
   beforeSend: function() {
                   jQuery("#container").fadeOut("slow", function() {
                       jQuery("#container").removeClass('error'); }
                   });
               },
   success:    function(data) {
                   jQuery("#container").html("success");
               },
   error:      function(req,status) {
                   jQuery("#container").html("error").addClass("error");
               },
   complete:   function() {
                   jQuery("#container").fadeIn();
               }
});
tvanfosson