I need assistance with positioning random elements inside a DIV. These elements have varying LEFT and TOP positions within the parent element
<div class="main"></div>
. How can I mathematically calculate and set these positions using JavaScript/jQuery to ensure that no random element goes beyond the boundaries of the parent container?
Here is an example of the HTML structure:
<div class="main"></div>
This is the JavaScript code snippet used to create and position the random elements:
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()))
});
});
You can view an example of this implementation here: https://jsfiddle.net/iahmadraza/u5y1zthv/
Thank you for your help!