Nested For loop to create a flexbox grid, not working

omar
Omar Zai
Published on Jan, 18 2024 1 min read 1 comments
image

I am currently working on the odin project's Etch-A-Sketch project. I'm trying to create a flexbox grid of divs to fit inside my set container. My first attempt was a single for loop that created the enough divs based on the input being squared, but the flex wouldn't wrap properly. Instead of creating a 16x16 grid, it would make 15 across and then 17/18 down, with space on the right side and bottom of the container.

I decided to try a new method of creating a set number of row divs with the set number of column divs inside each row. I thought having a nested for loop to create the rows with the set number of columns inside each row would work, but currently it only makes one row with one column div. Can someone help me with what I am missing?

 

const containerEl = document.getElementById('container');
let col = document.createElement('div');
let row = document.createElement('div');

function createGrid(input) {
    for(i = 0; i < input; i++) {
        
        row.classList.add('row');
        containerEl.appendChild(row);

        for(j = 0; j < input; j++) {
            
            col.classList.add('col');
            row.appendChild(col);
        }
        
    }
}

col.addEventListener('mouseover', function() {
    col.style.backgroundColor = 'black';
});

createGrid(16);
body {
    background-color: burlywood;
    
}

#heading {
    font-size: 100px;
    font-weight: 900;
    color: brown;
    text-align: center;
    padding: 60px;
}

#container {
    background-color: white;
    height: 960px;
    width: 960px;
    margin: auto;
}

.row {
    display: flex;
}

.col {
    border: 1px solid black;
    flex: 1;
}
<div id="heading">Etch-A-Sketch</div>
<div id="container"></div>
1 Answers

Mahabubur Rahman Jan 21, 2024 - 07:25 AM