0

I have the following code that shows a slideshow. My problem is that one element is not fully hidden (fadeout) before the next one (fade in) appaears, causing me to have to fix it with CSS, which is not the ideal scenario.. this is the code:

setInterval(function() { 
  $('#slides > li:first')
    .fadeOut(500)
    .next()
    .fadeIn(500)
    .end()
    .appendTo('#slidelist');
},  2000);

I've tried the following without success:

setInterval(function() { 
  $('#slides > li:first')
    .fadeOut(500).delay(500)
    .next()
    .fadeIn(500)
    .end()
    .appendTo('#slidelist');
},  2000);

Any ideas how can I get the element fully faded out before the next one fades in?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • Likely a duplicate: http://stackoverflow.com/a/1065809/3464723 - There are good answers in that thread that will definitely help you. Specifically, check out [.promise()](https://api.jquery.com/promise/) – Cody Reichert Oct 09 '14 at 05:11

1 Answers1

0

If you want the fadeIn to start after your previous fadeOut finishes, use the callback function parameter to execute the fadeIn. The callback function will execute after the first action (fadeOut) completes.

Here's an example of 2 divs - 1 fading out, then 1 fading in. I used the animate function on opacity, which is essentially the same as fadeIn / fadeOut.

Animate: http://api.jquery.com/animate/
FadeOut: http://api.jquery.com/fadeout/
FadeIn: http://api.jquery.com/fadein/

jsfiddle: http://jsfiddle.net/biz79/du9utty8/

var $divs = $('div');

$divs.eq(0).animate( {"opacity":"0"},1000 , function() {
    $divs.eq(1).animate( { "opacity":"1" },1000)
})

Hopefully you can modify your code to apply this solution. If not, post a fiddle and let me know, and I can help adjust your code.

Will
  • 1,299
  • 9
  • 9
  • I was looking for something I could insert into the function "chain" since I'm using the next() function to get the elements, if I break the chain it with a callback, I think I might have to store the current element in a variable and take the simplicity out of the current code. – sigmaxf Oct 09 '14 at 05:12
  • Yeah, I'm not sure if querying the dom on each iteration is better than querying once and updating an index instead. Either way, let me know if you find a better/more elegant solution. – Will Oct 09 '14 at 05:24