Tim Cutting
Tim Cutting

Reputation: 327

jQuery custom order for .each()

I am successfully using .each() to fade in some blocks one after the other. As expected it starts at the first element and moves on to the next in order.

Is there any way to control the order of .each()? Instead of 1,2,3,4 and so on I'd like, for example, 1,2,5,9,6,3,4,7,8.

$(window).load(function() {
    $(".blocks").each(function(i) {
       $(this).delay((i + 1) * 500).fadeIn(500);
    });
});

Upvotes: 0

Views: 6084

Answers (3)

jfriend00
jfriend00

Reputation: 707406

In a direct answer to your question, .each() iterates the items of a jQuery object in the order the items are in the jQuery internal array. There is no way to control the order that .each() uses other than changing the order in the array that it's iterating.

Since you don't disclose how the desired order would be determined algorithmically, your options are:

  1. Sort the array before .each() is called
  2. Manually create the desired order before the .each() call
  3. Some other piece of code that orders the array appropriately before the .each() call

In the very specific instance of your code snippet, you could solve it differently without reordering .each() or reordering the array by creating a lookup table that would look up the desired delay value for a given array index.

$(window).load(function() {
    var delayLookup = {1:1,2:2,5:3,9:4,6:5,3:6,4:7,7:8,8:9};
    $(".blocks").each(function(i) {
       var delayTime = delayLookup[i] || i;
       $(this).delay(delayTime * 500).fadeIn(500);
    });
});

Upvotes: 4

Elias Platek
Elias Platek

Reputation: 1114

You first have to sort your array the way you want, here it seems to be quite a random sorting so you have to create an array and fill elements manually. Then you can call the each function.

Upvotes: 0

Mitya
Mitya

Reputation: 34556

You don't say what the logic of your order is. If you meant random, you can do this:

$('.blocks')
    .sort(function(item) { return Math.floor(Math.random() * 2) === 1; })
    .each(function(i) {
        $(this).delay((i + 1) * 500).fadeIn(500);
    });

Upvotes: 1

Related Questions