tp9
tp9

Reputation: 341

Trying to delay a for loop until a div is loaded

I'm playing around with loading and moving around div elements on a page. I'm trying to fade in a string and then reverse it. The reverse loop needs to wait until after the initial fade in loop completes. Here is what I have so far but it doesn't execute the reverse loop. I assume because it can't see the initial divs yet.

var string_to_reverse = "Reverse",
i;

for (i = 0; i < string_to_reverse.length; i++) {
    $("<div>" + string_to_reverse[i] + "</div>").hide()
        .appendTo("body").delay(500 * i).fadeIn(1000);
}

$("body div:last").load(function () {
    for (i = 1; i <= $("body div").length; i++) {
        $("body div:eq(" + i + ")").detach().prependTo($("body"));
    }
});

http://jsfiddle.net/vk45U/

Upvotes: 3

Views: 346

Answers (2)

Tadeck
Tadeck

Reputation: 137390

What you are trying to do is wrong: you do not really know how much time something will take (you can only guess, sometimes making just an educated guess, but it is still a guess).

Instead of relying on current approach, please take a look at event-based approach to programming. In your case it could be using event handlers (eg. use "onload" event handler if you are loading some external content) or higher-order functions (using callbacks that will be called after you perform some actions, probably also by attaching them as part of vent handlers also).

More reading:

Upvotes: 1

Musa
Musa

Reputation: 97682

There is no load event on a div, so $("body div:last").load wouldn't do anything. You can pass a function to fadeIn to fire after the operation completes. Try adding the callback to the last animated div. A little messy but I'm sure you can clean it up

var string_to_reverse = "Reverse",
i;

for (i = 0; i < string_to_reverse.length; i++) {
    var dummy = function(){};
    $("<div>" + string_to_reverse[i] + "</div>").hide()
        .appendTo("body").delay(500 * i).fadeIn(1000, (i == string_to_reverse.length - 1)?rev:dummy);
}

function rev () {console.log('rev');
    for (var i = 1; i <= $("body div").length; i++) {
        $("body div:eq(" + i + ")").detach().prependTo($("body"));
    }
}

http://jsfiddle.net/mowglisanu/wXrC9/

Upvotes: 2

Related Questions