Jamie Jamie - 4 months ago 9
HTML Question

Can I order divs randomly at any point on a page using jquery?

Is it possible to place divs on a page in a random position on a page on load? if so.. how? Im getting a little stuck! or at least point me in the right direction.

I would like the page to load up with the divs I have already created in a random position. I dont mean in a random order like 3,5,2,7,9,1,4 etc in a row or column.

More like this example:
random images

In the above example the small red and white squares are draggable and the 2 larger ones are pots for the squares to be dragged in to.

Can the red and white smaller squares be randomaly placed?

examples I have previously found seem to explain how to make divs randomaly fade in or change after time to another random image.

I have only been coding a few weeks so bare with me a bit.

Many thanks,

Answer

Sure you can, here's a small example to get you started.

Find the width and height of the window, iterate over each div giving each an absolute position along with a random top and left property.

// get width and height of the page
var pwidth = $(window).width();
var pheight = $(window).height();

// loop through each div 
$('div').each(function(){
    // get random x and y positon
    var x = Math.random() * pwidth;
    var y = Math.random() * pheight;
    // set style options
    $(this).css('position', 'absolute').css('left', x).css('top', y);
});

This example doesn't randomize size or take the size of the element into account.