Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to place several elements randomly on page?
    primarykey
    data
    text
    <p>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:</p> <pre><code>$(".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 }); }); </code></pre> <p><a href="http://jsfiddle.net/7JGqZ/651/" rel="nofollow">http://jsfiddle.net/7JGqZ/651/</a></p> <p>So the problems I have:</p> <ol> <li><p>Don't know how to make it work with negative values — for example I need the top-margin to be from -150px to 300px.</p></li> <li><p>The elements in the fiddle beave a bit strange, like their positions are not really random or like they're connected to each other...</p></li> </ol> <p><strong>Update:</strong></p> <p>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:</p> <pre><code>$(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); } }); </code></pre> <p><a href="http://jsfiddle.net/7JGqZ/657/" rel="nofollow">http://jsfiddle.net/7JGqZ/657/</a> </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload