Thanks, now where’s that list.
[list=1][]What you’ll want is an array-like collection of the elements you want to be animated.
[]You can then randomize that collection.
[]You can then use a function that pops off one of the elements from that random collection and animates that element.
[]After the animation is completed, you can use the animations callback parameter, to call that same function, until there’s nothing left.[/list]
So, first thing - an array-like collection of the elements you want to be animated.
We can make that an actual array.
var shown = $(".shown").toArray();
Step 2 is to randomize them.
shown.sort(function () {
return (Math.round(Math.random())-0.5);
});
Now we have an array of randomly sorted items.
Step 3, is to use a function that pops off one of the elements from that random collection and animates that element
function performAnimation(arr) {
var el = arr.pop();
$(el).animate({left:'7px'}, 300);
$(el).animate({left:'0px'}, 300);
}
...
performAnimation(shown);
And step 4 is that after the animation is completed, you can use the animations callback parameter, to call that same function, until there’s nothing left.
function performAnimation(arr) {
var el = arr.pop();
$(el).animate({left:'7px'}, 300, function () {
performAnimation(arr);
});
$(el).animate({left:'0px'}, 300);
}
Let’s now tidy that up by moving the animate 0 part in to the same callback function, where the this keyword can be used, which also means that we don’t need the el variable anymore.
function performAnimation(arr) {
$(arr.pop()).animate({left:'7px'}, 300, function () {
$(this).animate({left:'0px'}, 300);
performAnimation(arr);
});
}
We can even tidy up the shown variable and sorting part, so that it now becomes:
performAnimation($(".shown")
.toArray()
.sort(function () {
return (Math.round(Math.random())-0.5);
})
);
The complete code after all of that is:
function performAnimation(arr) {
$(arr.pop()).animate({left:'7px'}, 300, function () {
$(this).animate({left:'0px'}, 300);
performAnimation(arr);
});
}
performAnimation($(".shown")
.toArray()
.sort(function () {
return (Math.round(Math.random())-0.5);
})
);