jQuery SlideUp & SlideDown Not Waiting

Being able to chain methods and actions together is a hugely powerful part of jQuery, there are some catch 22s however. This one plagued me a few times over the last couple of days, even after I had figured out the main cause the habit of simply thinking the next action will wait for the previous one is hard to kick, especially when it only doesn’t work in certain circumstances.

The main time you’ll stumble across this issue is using animated functions on elements and then trying to change the element.

$('#output').html('<p>You did a thing!</p>').slideDown(600).delay(2000).slideUp(600).html('<p>wait for it</p>');

Now this code will absolutely run it just doesn’t yield the results we really want, which is for the content of the output element to stay as “You did a thing” whilst it’s shown and change after the element has been hidden via slideUp(). Without going into to detail about the queue order for animations with jQuery, put simply the second .html() method fires way before we want it to. To fix this we introduce a anonymous function to process everything after the .slideUp() is complete.

$('#output').html('<p>You did a thing!</p>').slideDown(600).delay(2000).slideUp(600,function(){ $(this).html('<p>wait for it</p>'); });

Let the world know