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 : /
Thank you
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/iahmadraza/u5y1zthv/
Thank you
Share asked Mar 17, 2017 at 10:42 AhmadAhmad 1861 gold badge3 silver badges11 bronze badges 2- 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 Commented Mar 17, 2017 at 10:49
-
function getRnd(min, max)
withmin = 0
andmax = (main.width - box.width)
– Andreas Commented Mar 17, 2017 at 10:49
1 Answer
Reset to default 5The .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