I am having issues creating red and black divs

41 Views Asked by At

my task is to use loops to display two color div. I need it to have 12 rows and 8 columns. and the position needs to be absolute.

I am new at coding so this is a beginning assignment that I would like to learn, but I can't figure out how to do.

This is what I have so far,

    for(var j = 0; j < i; j++){

    }
}       
2

There are 2 best solutions below

0
Vedaant Arya On BEST ANSWER

JSFiddle: https://jsfiddle.net/Leyz1jgw/

Solution uses absolute positioning of <div>'s.

First, I defined a gen function, which creates a square of 35 by 35, at position (left, top) (top-left corner), and with background color color.

function gen(color, left, top)  {
    let redSq = document.createElement("div");   // my Div
    redSq.style.position = 'absolute';
    redSq.style.backgroundColor =  color;
    redSq.style.width = "35px" ;  // width
    redSq.style.height = "35px" ; // height
    redSq.style.left = left + 'px';
    redSq.style.top = top + 'px';
    document.body.appendChild(redSq);
}

Then, the looping goes like this: i determines the number of rows, j the number of columns.
The square in the i-th row (i is 0-based) will have i rows above it.

So, it should be at position 5 + i * (35 + 5) from the top, since the square has a side of 35 pixels, and the gap is supposed to be 5 pixels (including a starting gap).
Apply a similar logic for the horizontal positioning of the squares.

Now for the coloring: notice that for two consecutive (horizontal or vertical) squares, the colors are supposed to be different, and coincidentally, the sum i + j also changes parity accordingly. So color the square according to whether the sum is even or odd.

Here's the looping stuff:

for(i = 0; i < 12 ; i++){ //rows
    for(j = 0; j < 5; j++){ //columns
        let left = 5 + (j * 40); //positioning
        let top = 5 + (i * 40);
        if((i + j) % 2 == 0)  { //coloring
            gen('black', left, top);
        }  else  {
            gen('red', left, top);
        }
    }
}
0
imvain2 On

Using a single loop, you can use % modulus to determine if the cell is even/odd to turn it red/black and if its at the end of the row (8 cells) to create a new line.

    
for(var i = 0; i < 64 ; i++){ // foreloop
   
    var redSq = document.createElement("div");   // my Div
    redSq.style.backgroundColor =  (i % 2 == 0) ? "red" : "black";
    redSq.style.width = "35px" ;  // width
    redSq.style.height = "35px" ; // height
    redSq.style.margin = "5px";
    redSq.style.display = "inline-block";
    
    document.body.appendChild(redSq); // making sure the div appears
    
   if((i+1) % 8 == 0){
      document.body.innerHTML += "<br>";
   }
}