randomise position of elements within container

- 1 answer

Ad

I am trying to randomly position multiple child elements within a parent container using jquery/javascript. This is the code that I have at the moment. Any help or ideas would be great.

Bonus points if you can make the child never overlap.

HTML

<div class="container">
    <div class="population_man"></div>
    <div class="population_man"></div>
    <div class="population_man"></div>
</div>

CSS

.container{
    width:200px;
    height:200px;
    border:1px solid grey;
    position:relative;
}

.population_man{
    position:absolute;
    width:5px;
    height:10px;
    background-image:url('http://www.perthurbanist.com/wp-content/uploads/2015/12/Untitled-2.png');
}

JQUERY

$( document ).ready(function() {
$('.population_man').each(function(){
    $holder = $(this).parent();
    $divWidth = $holder.width();
    $divHeight = $holder.height();

       $(this).css({
            left: Math.floor(Math.random() * $divWidth),
            top: Math.floor(Math.random() * $divHeight)
       });        

})
});

jsfiddle: https://jsfiddle.net/zL97snxL/21/

Ad

Answer

Ad

Try this code. And on your jsfiddle, I am getting errors that jquery cannot be found. Click the "javascript" button add jQuery in the "frameworks and extensions" dropdown. After that, update and run again. It should work then :).

$( document ).ready(function() {
    $( '.population_man' ).each(function() {

        $holder    = $(this).parent();
        $divWidth  = $holder.width();
        $divHeight = $holder.height();

           $(this).css({
                'left': Math.floor( Math.random() * Number( $divWidth ) ),
                'top' : Math.floor( Math.random() * Number( $divHeight ) )
           });        

    })
});
Ad
source: stackoverflow.com
Ad