Casey Dwayne
Casey Dwayne

Reputation: 2169

Rotating testimonials using array in jquery

http://jsfiddle.net/jdTL9/1/

I'm having trouble getting this to work correctly. It changes text at the wrong time (as you can see in the demo). I think I'm going about this the wrong way (mainly setTimeout is unnecessary). Can someone take a look?

var testimonials = ['This', 'is', 'kind', 'of', 'working']

$.each(testimonials, function (i, val) {
  setTimeout(function () {
   //Slide In
    $('#testimonials blockquote').show("slide", {
      direction: "right"
    }, 1500, function () {
     //Slide Out
      $(this).text(val).hide("slide", {
          direction: "left"
      },
         1500);
    });
  }, i * 3000);
});

**I'd also like it to loop forever.

Upvotes: 1

Views: 444

Answers (1)

Fabrício Matté
Fabrício Matté

Reputation: 70169

You should change the text before displaying the item, could be in the .hide()'s callback or before show(). Also refactored your logic a bit to use callbacks instead of setTimeout:

var testimonials = ['This', 'is', 'kind', 'of', 'working'],
    i = 0,
    l = testimonials.length,
    $el = $('#testimonials blockquote');
(function loopTestimonials() {
    $el.text(testimonials[i++ % l]).show("slide", {
        direction: "right"
    }, 500, function () {
        $(this).delay(2000) //milliseconds to stay in screen
        .hide("slide", {
            direction: "left"
        }, 500, loopTestimonials); //restart show/hide loop when hide completes
    });
}());

Fiddle

Upvotes: 3

Related Questions