j roc
j roc

Reputation: 238

Arranging dynamically created divs in grid

I'm trying to build an etch a sketch,

the user receives a prompt to enter how many squares(divs) they would like in the grid, but I'm unable to organize those divs into a grid.

Heres my code (please note that I know the 'grid-template-rows' and 'grid-template-columns' are incorrect, that's just the point that I got to)

const container = document.getElementById('container')
const div = document.createElement('div')
const butt = document.getElementById('reset')


function changeColor() {

    event.target.setAttribute('style', 'background-color: #434141;')
}


function makeGrid(x) {

    x = prompt('how many squares (? by ?)')


    let i = 0;

    while (i < x * x) {

        let dye = document.createElement('div')
        dye.classList.add('dye')
        container.appendChild(dye)

        i++;

        dye.addEventListener('mouseover', changeColor)

        butt.addEventListener('click', () => {
            dye.setAttribute('style', 'background-color: grey;')
        })

    }

}
makeGrid()
#container {
    display: grid;
     grid-template-rows: auto;
     grid-template-columns: 1fr 1fr;
    background-color: #2196F3;
    width: 600px;
    height: 600px;
    margin: auto;
    margin-top: 60px;
    max-height: 600px;
    max-width: 600px;
   
}

.dye {
    background-color: grey;
    border: solid black 1px;
}



#reset{
    color: white;
    background-color: black;
    margin-left: 500px;
    margin-top: 20px;
    outline: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="container">
        
    </div>
<button id="reset">Reset Grid</button>
    <script src="index.js"></script>
</body>

</html>

Any help would be greatly appreciated!

Upvotes: 0

Views: 401

Answers (3)

xdeepakv
xdeepakv

Reputation: 8125

You can use flexbox, for better browser support and easy to use.

const container = document.getElementById("container");
const div = document.createElement("div");
const butt = document.getElementById("reset");

function changeColor() {
  event.target.style.backgroundColor = "#434141";
}

function makeGrid(x) {
  let num = prompt("how many squares (? by ?)");
  num = Number(num);
  const containerW = 600;
  for (let i = 0; i < num * num; i++) {
    let dye = document.createElement("div");
    dye.classList.add("dye");
    dye.style.flexBasis = `${Math.floor(containerW / num - 4)}px`;
    dye.style.height = `${Math.floor(containerW / num - 4)}px`;
    dye.addEventListener("mouseover", changeColor);
    container.appendChild(dye);
  }
  butt.addEventListener("click", () => {
    document
      .querySelectorAll(".dye")
      .forEach(dye => (dye.style.backgroundColor = "grey"));
  });
}
makeGrid();
#container {
  display: flex;
  flex-wrap: wrap;
  background-color: #2196F3;
  justify-content: space-evenly;
  width: 600px;
  height: 600px;
  margin: auto;
  margin-top: 60px;
  max-height: 600px;
  max-width: 600px;
}

.dye {
  background-color: grey;
  border: solid black 1px;
}

#reset {
  color: white;
  background-color: black;
  margin-left: 500px;
  margin-top: 20px;
  outline: none;
}
.snippet-result-code {
 height: 700px!important;
}
<div id="container">

    </div>
    <button id="reset">Reset Grid</button>
    <script src="app.js"></script>

Upvotes: 1

Iman Emadi
Iman Emadi

Reputation: 420

you don't need to declare an event each time your loop executes
also you can use .style.backgroundColor to change BGC instead of assigning new style property

function changeColor() {
    event.target.setAttribute('style', 'background-color: #434141;')
}


function makeGrid() {

    x = prompt('how many squares (? by ?)')
    let z = 0;
    while (z < x * x) {

        let dye = document.createElement('div')
        dye.classList.add('dye')
        container.appendChild(dye)
        z++;
    }

    let squares = document.getElementById('container').querySelectorAll('.dye');
    for (j = 0; j < squares.length; j++) {
        squares[j].addEventListener('mouseover', changeColor)
    }

    document.getElementById('reset').addEventListener('click', () => {
        for (i = 0; i < squares.length; i++) {
            // squares[i] = each  dye element
            squares[i].style.backgroundColor = 'gray';
        }
    });
}
makeGrid()
      #container {
        display: grid;
        grid-template-rows: auto;
        grid-template-columns: 1fr 1fr;
        background-color: #2196f3;
        width: 600px;
        height: 600px;
        margin: auto;
        margin-top: 60px;
        max-height: 600px;
        max-width: 600px;
      }

      .dye {
        background-color: grey;
        border: solid black 1px;
      }

      #reset {
        color: white;
        background-color: black;
        margin-left: 500px;
        margin-top: 20px;
        outline: none;
      }
    <div id="container"></div>
    <button id="reset">Reset Grid</button>

Upvotes: 1

S&#248;lve
S&#248;lve

Reputation: 4396

You can change the grid template columns via javascript to dynamically add number of columns using the repeat value.

document.getElementById('container').style.gridTemplateColumns = `repeat(${x}, 1fr)`

const container = document.getElementById('container')
const div = document.createElement('div')
const butt = document.getElementById('reset')


function changeColor() {

    event.target.setAttribute('style', 'background-color: #434141;')
}


function makeGrid(x) {

    x = prompt('how many squares (? by ?)')


    let i = 0;
    
    document.getElementById('container').style.gridTemplateColumns = `repeat(${x}, 1fr)` 

    while (i < x * x) {

        let dye = document.createElement('div')
        dye.classList.add('dye')
        container.appendChild(dye)

        i++;

        dye.addEventListener('mouseover', changeColor)

        butt.addEventListener('click', () => {
            dye.setAttribute('style', 'background-color: grey;')
        })

    }

}
makeGrid()
#container {
    display: grid;
     grid-template-rows: auto;
     grid-template-columns: 1fr 1fr;
    background-color: #2196F3;
    width: 600px;
    height: 600px;
    margin: auto;
    margin-top: 60px;
    max-height: 600px;
    max-width: 600px;
   
}

.dye {
    background-color: grey;
    border: solid black 1px;
}



#reset{
    color: white;
    background-color: black;
    margin-left: 500px;
    margin-top: 20px;
    outline: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="container">
        
    </div>
<button id="reset">Reset Grid</button>
    <script src="index.js"></script>
</body>

</html>

Upvotes: 2

Related Questions