Frage

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!

War es hilfreich?

Lösung

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/

Andere Tipps

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top