angel_30
angel_30

Reputation: 1

Adding delay to DIV animation

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/54hqm/3/

Now I want to happen after each click, is basically to move each DIV one after another, with a delay, instead of moving the whole stack of DIVs at once. I don't exactly know what to do. Can anyone help me with that?

$(document).ready(function () {

    var count = 0;
    var items = 0;
    var packetNumber = 0;
    var speed = 0;
    $("button").click(function () {

        if (count < 4) {
            items = items + 1;
            count++;
        } else {
            items = items * 2;
        }

        speed = $("#speed").val();
        createDivs(items);
        animateDivs();
    });

    function createDivs(divs) {
        packetNumber = 1;
        var left = 60;
        for (var i = 0; i < divs; i++) {
            var div = $("<div class='t'></div>");
            div.appendTo(".packets");
            $("<font class='span'>" + packetNumber + "</font>").appendTo(div);
            packetNumber++;
            div.css("left",left+"px");

            div.hide();
            left += 20;
        }
    }

    function animateDivs() {
        $(".t").each(function () {
            var packet = $(this);

            packet.show();

            packet.animate({
                left: '+=230px'
            }, speed);

            packet.animate({
                left: '+=230px'
            }, speed);

            packet.animate({
                top: '+=20px',
                backgroundColor: "#f09090",
                text: '12'
            }, speed / 4, "swing", function () {

                $('.span').fadeOut(100, function () {

                    $(this).text(function () {
                        return 'a' + $(this).text().replace('a', '');
                    }).fadeIn(100);

                });

            });
            packet.delay(1000).animate({left:'-=230px'}, speed);
            packet.animate({left:'-=230px'}, speed);
        }).promise().done(function(){
        $(".packets").empty();});

    }
});

Upvotes: 1

Views: 130

Answers (1)

zord
zord

Reputation: 4783

You can make this with 2 small modifications:

  1. In your each() function, add the index parameter to know the index of the currently animating packet:

    $(".t").each(function (index) {

  2. Before your animate calls, insert a packet.delay() with a delay increasing with every item:

    packet.delay(index * 250);

I updated your fiddle to show results.
Update: I made a second version based on your comment.

Upvotes: 2

Related Questions