Siamak
Siamak

Reputation: 45

jQuery each: loop an array, append texts and do animations by jQuery

I have an array like:

var txt = new Array('1st', '2nd', '3rd');

I need to put this array into a loop, apply each text to a (common) div, show it with an animation, then hide it with another animation.

What I have done is, first added an html div:

<div id="contentHolder"></div>

Then in my jQuery code, I wrote:

$.each(txt, function(index, value)) {
    $("#contentHolder").empty().append(value).slideDown('slow').fadeOut('slow');
}

What I get is that the contentHolder div is filled with the "3rd" and it appears and disappears for three times! It looks like the text is being applied in the loop and when it's done, the queue of animations is being run.

Here is its code: http://jsfiddle.net/fbgp2000/97ThY/2/

What I need is the same but showing different texts in each loop.

Could anyone please tell me what I'm missing?

Upvotes: 2

Views: 1968

Answers (3)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to use recurion and call backs in this context, since .animate() is asynchronous.

Try this,

var txt = new Array("1st", "2nd", "3rd");
var xCnt = -1;

function AnimateOneByOne()
{
    xCnt += 1; 

    if( xCnt < txt.length){

       $("#contentHolder")
      .empty()
      .append(txt[xCnt])
      .slideDown('slow')
      .fadeOut('slow', AnimateOneByOne);

    }

}

AnimateOneByOne();

DEMO

Upvotes: 2

Ram
Ram

Reputation: 144709

You should use callback function here, which is called when the animation is complete, your loop runs much faster than the animations:

var $contentHolder = $('#contentHolder');
(function worm(i) {
    $contentHolder.fadeOut(function() {
        $(this).text( txt[i] ).slideDown(function() {
            txt.length !== ++i ? worm(i) : '_the end';
        });
    }); 
})(0);

http://jsfiddle.net/WW3cH/

For restarting:

worm( txt.length !== ++i ? i : 0 );

http://jsfiddle.net/W4fm9/

Upvotes: 1

php_nub_qq
php_nub_qq

Reputation: 16055

A rather simple solution

var txt = new Array('1st', '2nd', '3rd'),
    item = 0,
    t = setInterval(function(){

    $("#contentHolder").html(txt[item]).slideDown(1000).fadeOut(1000);
    item++;
    if(item>txt.length){
        clearInterval(t);
        item = 0; // for further use;
    }
}, 2000);

Upvotes: 1

Related Questions