Ahmad
Ahmad

Reputation: 186

random position of elements inside parent div

I have floating RANDOM elements inside DIV, varying LEFT and TOP position inside parent <div class="main"></div>. How to calculate and set LEFT and TOP positions mathematically in javascript/jQuery so any random element will NOT go beyond boundary defined parent

HTML :

<div class="main"></div>

Javascript :

for (var i = 0; i < 5; i++) {
  $('.main').append('<div class="box"></div>');
}
$( '.box' ).each(function( index ) {
  $(this).css({
    left : ((Math.random() * $('.main').width())),
    top : ((Math.random() * $('.main').height()))
  });
});

Example : https://jsfiddle.net/iahmadraza/u5y1zthv/

Thank you

Upvotes: 3

Views: 11494

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The .box elements are fixed at 100px height and width, so to achieve what you need just remove that dimension from the possible random value maximum:

$(this).css({
  left: Math.random() * ($('.main').width() - $(this).width()),
  top: Math.random() * ($('.main').height() - $(this).height())
});

Updated fiddle

Upvotes: 5

Related Questions