Reputation: 377
Please Consider the following:
html:
<div class="circle"> </div>
css:
.circle{
position:fixed;
width:100px;
height:100px;
border:none;
border-radius:50px;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
background-color: red;}
jquery:
$(document).ready(function(){
var cArray=[];
for(var i=0; i<7; i++){
var c=$('.circle').clone().appendTo('body');
cArray.push(c);
}
animateCircle(cArray);
});
function getNewPosition(){
var h= $(window).height()-100;
var w= $(window).width()-100;
var nh=Math.floor(Math.random()*h);
var nw=Math.floor(Math.random()*w);
return [nh,nw];
}
function animateCircle(cArr){
$.each(cArr, function(index,value){
var newp = getNewPosition();
$(this).animate({ top: newp[0],left: newp[1],function(){animateCircle();} });
});
}
With the above code,i have created a circle,cloned it and added each new element to cArray
as you can see.The problem is that all the cloned circles are animated only once,they're supposed to keep moving each time a new position is acquired,but obviously i got something wrong.Thanks in advance.
Upvotes: 0
Views: 44
Reputation: 33409
$(this).animate({ top: newp[0],left: newp[1],function(){animateCircle();} });
This is the problematic line. 1, there's a syntax error. 2, there's a logic error.
Syntax error, you didn't close the object in the right place.
$(this).animate({ top: newp[0],left: newp[1]}, function(){animateCircle();});
// ^^
Logic error, animateCircle
takes an argument with an array (cArr
):
$(this).animate({top: newp[0], left: newp[1]}, function(){animateCircle(cArr);});
Upvotes: 1