I want to place several elements of one class randomly on the page with Javascript / jQuery. My idea is to generate random values for margin-top, margin-left and z-index. The problem is that I need to generate values in between negative and positive (like from -150px to 300px) and I don't understand how to make it with the code I use:
$(".randomnumber").each(function () {
var randomtop = Math.floor(Math.random() * 101);
var randomleft = Math.floor(Math.random() * 101);
var randomzindex = Math.floor(Math.random() * 101);
$(this).css({
"margin-top": randomtop,
"margin-left": randomleft,
"z-index": randomzindex
});
});
http://jsfiddle.net/7JGqZ/651/
So the problems I have:
Don't know how to make it work with negative values — for example I need the top-margin to be from -150px to 300px.
The elements in the fiddle beave a bit strange, like their positions are not really random or like they're connected to each other...
Update:
Made it work, but still don't like the result, I actually would like elements to be placed randomly so they would fit the page size, I mean that elements would be placed all over the page, not going too far above the edge of the page. Now I have a parent element that is fixed in the centre of the page (has width and height = 0, top and bottom = 50%), and my idea was to position its child elements with generating top and left margins somehow like this:
$(document).ready(function(){
$(".mood-img").each(function () {
var height = $(window).height();
var halfheight = height/2;
var margintop = halfheight-400;
var width = $(window).width();
var halfwidth = width/2;
var marginleft = halfwidth-500;
var randomtop = getRandomInt(halfheight, margintop);
var randomleft = getRandomInt(halfwidth, marginleft);
var randomzindex = getRandomInt(1, 30);
$(this).css({
"margin-top": randomtop,
"margin-left": randomleft,
"z-index": randomzindex
});
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
});