0

I've got this code and it works great to fade in and out one div at a time. I need to fade out two divs at a time, and replace them with the next two.

$(function() {
    // Set first div to show
    $('.testimonials div:first').show();

    // Begin the loop, fade out, find next div, fade that div in, end the process and append back to main div.
    setInterval(function() {
        $('.testimonials div:first-child').fadeOut().next('div').fadeIn().end().appendTo('.testimonials');
    }, 5000);
)};

I tried to improve the script:

The fading is working - it fades out the first two, and fades in the next two. But it never loops!

$(function() {
    // Set first div to show
    $('.testimonials .quote:lt(2)').show();

    // Begin the loop, fade out, find next div, fade that div in, end the process and append back to main div.
    setInterval(function() {
        $('.testimonials .quote').slice(0,2).fadeOut().nextAll('.quote').slice(3,4).(.fadeIn().end().appendTo('.testimonials');
    }, 5000);
)};

The fading is working - it fades out the first two, and fades in the next two. But it never loops!

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user1051532
  • 129
  • 1
  • 8

2 Answers2

2

A somewhat different approach:

$(function () {
  (function anim(num, delay) {
    $('.testimonials .quote').slice(0, num).fadeIn().delay(delay).fadeOut().promise().done(function () {
      $('.testimonials').append(this);
      anim(num, delay);
    });
  }(2, 2000)); // change these values to fade another number of elements, or
               // have a longer delay between the fades
});

demo: http://jsbin.com/ivuyex/5/

Yoshi
  • 54,081
  • 14
  • 89
  • 103
0

With the setInterval you always fadeOut the first two and fadeIn the third and fourth. It does loop, but after the the first iteration there is just nothing more to change.

You can try fadeToggle() after you initally set the states:

setInterval(function() {
    $('.testimonials .quote').fadeToggle().end().appendTo('.testimonials');
 }, 5000);
nxtwrld
  • 1,942
  • 14
  • 15
  • Ah right, that makes sense. I actually tried it like this and it seems to be working, all the fading isn't very smooth. There's now a "jump" in between. You can see it in action on the URL above (layer3.waltercrow.co.nz) – user1051532 Nov 14 '12 at 09:43
  • I see what you mean. It needs to fadeOut first and fadeIn after. Yoshi's solution works great for that. – nxtwrld Nov 14 '12 at 09:49