0

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

}
1
  • And what is not working like you expect in your code? Commented Aug 20, 2019 at 20:44

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.