I have the following jQuery code:
var id = $(this).data('id');
if ($('#container').is(':visible'))
{
$('#container').slideToggle('fast', function() {
$('#' + id).toggle();
});
}
else
{
$('#' + id).toggle(0, function() {
$('#container').slideToggle('fast');
});
}
This code is contained within a much larger method which I will not post here. The method is responsible for toggling between the style and behaviour of a set of buttons, and in the above code, a container is displayed/hidden when a button is pressed. If a button is currently pressed down (hence a container is displayed) but the user clicks another button, the above method is called first on the currently pressed button to hide its container and then on the button that was just clicked to show its container.
The problem is that the animation for the currently pressed button doesn’t finish (or doesn’t even seem to start as I observed whilst debugging) before the method is executed for the button just pressed.
Does anyone know how to make the code wait for the animation queue to empty before returning from this method?
You should work with the
Deferred/promiseobject which is provided by jQuery for animated elements (alongside other things, like XHR requests).That means, you can always hook into a promise like so
and then call it like
Demo: http://jsfiddle.net/dCVnG/