0

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 cArrayas 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.

2
  • $(this).animate({ top: newp[0],left: newp[1],function(){animateCircle();} }); is invalid Javascript. Commented Jan 25, 2015 at 14:52
  • i know there's something wrong,do you know how i can fix it? thanks Commented Jan 25, 2015 at 14:54

1 Answer 1

1
$(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);});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.