36

There's a bunch on this topic, but I havn't found an instance that applies well to my situation.

Fade a picture out and then fade another picture in. Instead, I'm running into an issue where the first fades out and immediately (before the animation is finished) the next fades in.

I read about this once and can't remember exactly what the trick was..

http://jsfiddle.net/danielredwood/gBw9j/

thanks for your help!

technopeasant
  • 7,309
  • 26
  • 86
  • 146

4 Answers4

82

fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:

$('#two, #three').hide();
$('.slide').click(function(){
    var $this = $(this);
    $this.fadeOut(function(){ $this.next().fadeIn(); });
});

alternatively, you can just "pause" the chain, but you need to specify for how long:

$(this).fadeOut().next().delay(500).fadeIn();
Mark Kahn
  • 81,115
  • 25
  • 161
  • 212
  • Ah, that's right. Thanks for the reminder. now that fadeOut has a function attached, where can I adjust it's speed? fadeIn's easy :) – technopeasant Jun 09 '11 at 02:16
  • 7
    `fadeOut('fast', function(){ ... })` or `fadeOut(200, function(){ ... })` – Mark Kahn Jun 09 '11 at 02:17
  • Downvoting. `next()` does not do what this answer assumes it does. See the documentation: https://api.jquery.com/next/ – David Oct 29 '18 at 17:00
  • 1
    @David - `next()` isn't what this answer is about, it's talking about the callback and `.delay()`, `next()` is just part of OP's specific solution. Please bother to understand answers before downvoting them and being snarky – Mark Kahn Nov 20 '18 at 22:39
  • Thanks @MarkKahn. I would remove the downvote if I could. Sorry for snarking on you. I obviously did not take the time to understand the question. My apologies. – David Nov 21 '18 at 00:46
5

After jQuery 1.6, using promise seems like a better option.

var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
  fadeoOutDone.then(function(){
    $div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
    $div1.fadeIn();
  });
});
rabbit.aaron
  • 1,648
  • 13
  • 21
2

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

Dr1Ku
  • 2,690
  • 3
  • 43
  • 52
  • Here is few more collection of fadein fadeout example http://webdevlopementhelp.blogspot.in/2009/09/jquery-fade-in-fade-out-effect.html – kiran Oct 21 '13 at 11:00
0

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}
Flimm
  • 97,949
  • 30
  • 201
  • 217