javascript - How to create grid and place elements randomly inside column? -


i have responsive grid created js , css. inside each column in grid want place elements (the red squares), squares should placed randomly , inside of columns. there 50 columns, let's want place 20 squares randomly inside columns squares can't overlap. how achieve in best way?

js

var grid = document.getelementbyid("grid");  for(var = 0; < 50; i++) {     var square = document.createelement("div");     square.classname = 'square';     grid.appendchild(square);      var child = document.createelement("div");     child.classname = 'child';     square.appendchild(child); } 

fiddle

first add id each square, idea generate random number between 0 , 49 able access squares. each time add square, have store index check whether has been added. stop until 20 squares added.

var field = document.getelementbyid("field");    (var = 0; < 50; i++) {    var square = document.createelement("div");    square.classname = 'square';    square.id = 'square' + i;    field.appendchild(square);  }    var squaresplaced = []; // stores squares index placed    while (squaresplaced.length < 20) { // stop if 20 squares added    var randomindex = parseint(49 * math.random()); // generate random number between 0 , 49      // add square if doesn't exist    if (squaresplaced.indexof(randomindex) === -1) {      squaresplaced.push(randomindex);      document.getelementbyid('square' + randomindex).style.bordercolor = 'red';    }  }
html,  body {    margin: 0;    height: 100%;  }    #field {    width: 60vw;    height: 60vw;    margin: 0 auto;    font-size: 0;    position: relative;  }    #field>div.square {    font-size: 1rem;    vertical-align: top;    display: inline-block;    width: 10%;    height: 10%;    box-sizing: border-box;    border: 1px solid #000;  }    #field>div.circle {    font-size: 1rem;    vertical-align: top;    display: inline-block;    width: 10%;    height: 10%;    box-sizing: border-box;    border: 1px solid #f00;    border-radius: 100px;  }
<div id="field"></div>


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -