caulwell164
caulwell164

Reputation: 1

How to create a css grid with javascript with a variable number of "cells"?

I am trying to (in Javascript)

  1. Style a div as a CSS Grid in which the number of rows and columns can change (dependent on a future prompt element).

  2. Default this Grid to be 16x16 when the page first loads.

  3. Create and append divs to this grid that will fill all the grid areas. e.g. in the 16x16 grid, there will be 256 created divs.

I tried to do this via a loop. As demonstrated below:

 <div class = "grid"> </div>
.grid{
    height: 70vh;
    width: 80vw;
}
const gridContainer = document.getElementsByClassName("grid");

let rowtot = 16;
let celltot = rowno * rowno;

gridContainer.style.display = "grid";
gridContainer.style.gridTemplateRows = `repeat(${rowtot}, 1fr)`;
gridContainer.style.gridTemplateColumns = `repeat(${rowtot}, 1fr)`;

let row = 1;
let column = 1;
for(let i = 1; i <= celltot; i++){
    let cell = document.createElement("div");
    cell.style.border = "1px solid black";
    cell.style.gridRow = row;
    cell.style.gridColumn = column;
    column +=1;
    if (column == 16){
        row += 1;
        column = 1;
    }
    gridContainer.appendChild(cell);

}

Upvotes: 0

Views: 1528

Answers (1)

Grzegorz T.
Grzegorz T.

Reputation: 4113

Maybe that way ;)

let gridContainer = document.querySelector('.grid');

let rowtot = 16;
let celltot = rowtot * rowtot;

gridContainer.style.display = 'grid';
gridContainer.style.gridTemplateRows = `repeat(${rowtot}, 1fr)`;
gridContainer.style.gridTemplateColumns = `repeat(${rowtot}, 1fr)`;

let row = 1;
let column = 1;
for (let i = 1; i <= celltot; i++) {
  let cell = document.createElement('div');
  cell.style.border = '1px solid black';
  cell.style.gridRow = row;
  cell.style.gridColumn = column;
  cell.textContent = i;
  column += 1;
  if (column === rowtot + 1) {
    row += 1;
    column = 1;
  }
  gridContainer.appendChild(cell);
}
.grid {
  height: 70vh;
  width: 80vw;
}
<div class="grid"> </div>

Upvotes: 1

Related Questions