Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 204
Ahmad Avatar asked Dec 04 '25 15:12

Ahmad


1 Answers

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

like image 149
Rory McCrossan Avatar answered Dec 07 '25 05:12

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!