The problem: I have a simple function and I need the instructions within it to take place one at a time. Here it is:
showImages = (current_time, exercise) ->
$('#slideshow img.active').first().fadeOut(500).removeClass('active')
$('#new-image').addClass('active')
Since the last 2 lines happen almost simultaneously, the image with id 'new-image' gets faded out.
I would like the line processing the img with the class 'active' to be completed before the next line kicks in.
I have done lots of Google searching but I don't know how to apply the code examples to this use case. Here are some Google articles I found:
- jQuery: wait for function to complete to continue processing?
- http://www.sitepoint.com/forums/showthread.php?847638-Script-to-Wait-for-javascript-function-to-end
- waiting a function to complete
Your help would be greatly appreciated.
jQuery's fadeOut()
method has a complete callback which can be used as a function:
.fadeOut( [duration ] [, complete ] )
This can be used as:
$(elem).fadeOut(500, function() { ... });
Therefore, in your case you can simply:
$('#slideshow img.active').first().fadeOut(500, function() {
$(this).removeClass('active');
$('#new-image').addClass('active');
});
With this, the currently .active
element will lose its class and the #new-image
will gain the active class after the fadeOut()
has finished.
Use the fadeOut()
complete function:
$('#slideshow img.active').first().fadeOut(500, function() {
$(this).removeClass('active');
$('#new-image').addClass('active');
});
Any code within the complete
function is executed when the animation has finished
try this hope this helps. heres a quick jsFiddle
$('#slideshow img.active').first()
.fadeOut(500).removeClass('active')
.setTimeout(function(){
$('#new-image').addClass('active')
},100);