icsharpcode

I am having issues creating red and black divs


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++){

    }
}       

Solution

  • 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);
            }
        }
    }