Reputation: 2683
I need to know, how can I run one function for each element I select. This is my jQuery code:
$(function() {
$(".line").each(function() {
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot);
}, 250);
});
});
It could run moveDot()
for each element (every after 250ms), but now, all elements starts at the same time. Here is JSFIDDLE.
Upvotes: 0
Views: 59
Reputation: 2175
I will prefer like this as one of solution:
function moveDot(elm,index) {
elm.animate({left: '370px'}, {duration: 3000*index, queue: false, done: function() {
elm.animate({left: '0px'}, {duration: 3000*index, queue: false, done: function() {
moveDot(elm,index)
}});
}});
}
$(function() {
$(".line").each(function(i) {
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot,++i);
}, 250);
});
});
Upvotes: 0
Reputation: 20626
Try passing index
to setTimeout()
. It would increment for each element in the loop, and thus add to the delay.
$(function() {
$(".line").each(function(index) {
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot);
}, index * 250);
});
});
Upvotes: 2
Reputation: 727
You can use random function javascript
(function() {
$(".line").each(function() {
var x = Math.floor((Math.random() * 250) + 1);
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot);
}, x);
});
});
Upvotes: 0
Reputation: 15393
Multiply with each index
$(".line").each(function(i) {
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot);
}, 250 * i+1);
});
Upvotes: 2
Reputation: 144689
Use the indices:
$(".line").each(function(i) {
var dot = $(this).find('.dot');
setTimeout(function () {
moveDot(dot);
}, ++i * 250);
});
Upvotes: 2