3

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

ahmad.ideveloper
  • 186
  • 1
  • 2
  • 11
  • You have to remove the amount of width/height of the element itself. left : ((Math.random() * ($('.main').width()-$(this).width()))), top : ((Math.random() * ($('.main').height()-$(this).height()))) – Roy Bogado Mar 17 '17 at 10:49
  • [`function getRnd(min, max)`](https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range) with `min = 0` and `max = (main.width - box.width)` – Andreas Mar 17 '17 at 10:49

1 Answers1

5

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339