Stoyan Zdravkov
Stoyan Zdravkov

Reputation: 95

Jquery random position to multiple divs

that is my code http://jsfiddle.net/BREvn/2/ (it works) but i want everyone div to be with unique position coordinates. Now script get the first and others move to him place. How can be possible to fix this problem? I tryed a .each function but there wasn't any results. I think this will be easy but i'm to too good in jquery/javascript.

$('#latestblock').animate({
  top: newY,
  left: newX
}, 500, function() { });

I think here must be in loop but dont know how to do it.

Upvotes: 0

Views: 9302

Answers (3)

Ferry Kobus
Ferry Kobus

Reputation: 2029

Something like this?

http://jsfiddle.net/BREvn/5/

I renamed the id to a class and created an infinite loop. Also send the object into the moveRandom function 'moveRandom(obj)' and after de animation finishes, recall the moveRandom function with itself.

$('.latestblock').each(function() {
    moveRandom($(this));
});

Upvotes: 2

Brian Salta
Brian Salta

Reputation: 1576

Here is the updated and working version: http://jsfiddle.net/BREvn/4/

An ID must be unique, you cannot have 3 elements with the same id='latestblock'

I also called the function three times and made sure the function was using that parameter passed in.

moveRandom('#latestblock1');
moveRandom('#latestblock2');
moveRandom('#latestblock3');

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382092

You can't give the same id to more than one element.

You could use a class

<div id='container'>
  <div class='latestblock'></div>
  <div class='latestblock'></div>
  <div class='latestblock'></div>
</div>

and then use each to animate all elements :

$('.latestblock').each(function(){ // <= iterates on all blocks
   moveRandom($(this)); // <= pass the block to the moveRandom function
});

Complete demo

Upvotes: 1

Related Questions