html:

<div></div> 

css:

 div { width: 5px; height: 5px; background: #fff; } 

js:

 for(var i=0; i<10; i++) { $('body').append('<div>');} // тут код для рандомной позиции } 

It is necessary to make each block a random position from the beginning of the site (top, left);

  • The essence of the issue is not clear. Do you need a position in the DOM or just left top? - Yuri
  • I do not even know what to say. I want the div to be in the position top: 50px for example and left: 120px; - goodalien

2 answers 2

Math.random generates a random number from 0 to 1.

css() sets styles to a specific element

 for(var i=0; i<10; i++) { div=$('<div></div>'); div.appendTo('div#main').css({left:Math.random()*200+'px',top:Math.random()*200+'px'} ) } 
 div { width: 5px; height: 5px; background: red; position:absolute; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id=main></div> 

    You can use Math.random to do this:

     $(function() { for(var i = 0; i < 10; i++) { $('body').append('<div style="top: '+Math.random() * 400+'px; left: '+Math.random() * 400+'px"></div>'); } }); 
     div { position: absolute; width: 10px; height: 10px; background: black; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>