I wanted an animation where i assign random left and top values to divs and animate them, but also wanted the animation to restart after finishing. so i fired the animate function inside itself, but after the first animation, only the last repeating div element was animating. I did like this:
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
$(".dot").each(function(){
var abc = getRandomArbitrary(0,100);
var xyz = getRandomArbitrary(0,100);
var aaa = getRandomArbitrary(0,100);
var yyy = getRandomArbitrary(0,100);
$(this).css({"left": abc+"%", "top": xyz+"%"})
$thiss = $(this);
for(var i=0; i< $(".dot").length;i++){
function anim(){
$thiss.animate({"left":yyy+"%", "top": aaa+"%"},1000,function(){
anim();
});
console.log(i)
}
}
anim();
});
html:
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
css:
.dot{width: 8px; height: 8px; border-radius: 100%; background: red; position: absolute;}
jsfiddle: https://jsfiddle.net/qfcmfzw7/ fiddle where i didnot use the 'for': https://jsfiddle.net/744sx34v/
<>snippet