Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery callback not waiting on fadeOut

It seems to me the following code should produce these results:

mademoiselle
demoiselle
mesdemoiselles

Instead, as "ma" fades out, "mes" fades in making the sequence:

mademoiselle
madesdemoiselles
mesdemoiselles

The code:

<span class="remove">ma</span><span class="add">mes</span>demoiselle<span class="add">s</span>

$(document).ready(function() {
   $(".remove").fadeOut(4000,function(){
       $(".add").fadeIn(5000);      
   });
});

Edit: I found an empty span that if I remove makes the bug go away:

<span class="remove">ma</span><span class="add">mes</span>demoiselle<span class="remove"></span><span class="add">s</span>

The problem is: The php code generating this is using the spans as placeholders. I'll str_replace them if I have to, but I'm curious why this is happening.

like image 382
Stephane Avatar asked Nov 05 '09 02:11

Stephane


2 Answers

Ok, so I managed to reproduce your problem see the example at http://jsbin.com/ocaha.

What's happening is that jQuery can see that your empty <span> does not need to be faded out. Therefor it considers the animation done and executes for 0ms instead of the expected 4000ms. So it immediately starts fading in all of the .adds.

To prevent this behaviour, I would filter away all empty elements from the selection. Like this:

$(document).ready(function() {
   $(".remove")
               .filter(function(){ return ! $(this).is(":empty"); })
               .fadeOut(4000, function(){
     $(".add").fadeIn(5000);
   });
});

See working example at http://jsbin.com/ovivi.

like image 177
Martin Nycander Avatar answered Nov 08 '22 11:11

Martin Nycander


Change ":empty" to ":hidden" if not working:

$(document).ready(function() {
   $(".remove")
               .filter(function(){ return ! $(this).is(":hidden"); })
               .fadeOut(4000, function(){
     $(".add").fadeIn(5000);
   });
});
like image 34
Davide De Maestri Avatar answered Nov 08 '22 10:11

Davide De Maestri