0

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:

Your help would be greatly appreciated.

Community
  • 1
  • 1
allesklar
  • 9,506
  • 6
  • 36
  • 53
  • _"Since the last 2 lines happen almost simultaneously, the image with id 'new-image' gets faded out."_ - That doesn't make sense. The line `$('#slideshow img.active').first().fadeOut(500).removeClass('active')` selects the first `img.active` element (within `#slideshow`) and queues up a fadeOut on it before immediately removing its `'active'` class. The fadeOut takes 500ms, but will apply _only_ to that element, it doesn't somehow also apply to other elements that may have the `'active'` class added while the fade is still happening. – nnnnnn May 29 '13 at 10:40
  • P.S. Is there other code that you're not showing? – nnnnnn May 29 '13 at 10:47

3 Answers3

1

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

billyonecan
  • 20,090
  • 8
  • 42
  • 64
1

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.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

try this hope this helps. heres a quick jsFiddle

    $('#slideshow img.active').first()
    .fadeOut(500).removeClass('active')
    .setTimeout(function(){
      $('#new-image').addClass('active')
    },100);
Lewis E
  • 327
  • 1
  • 7