Working through the etch-a-sketch solution in The Odin Project. I have a working solution, but need to take an input and once entered, the existing grid should be removed and a new grid should be generated in the same total space as before.
Can I ask grid-template-columns to take a variable? The 16 needs to be dynamic and I need it to match what I'm taking in from the user input on the JS side.
body {
justify-content: center;
display: flex;
flex-direction: column;
align-items: center;
background-color: white;
}
.container {
display: grid;
grid-template-columns: repeat(16, 1fr);
grid-template-columns: repeat(auto-fill, 1fr);
text-align: center;
border: 1px solid black;
}
.buttons {
display: flex;
justify-content: center;
}
button {
padding: 10px;
margin: 10px;
width: 150px;
text-align: center;
}
.black {
background-color: black;
}
See Javascript below. I'm going to add a function for calling the user input, but at this point it's still just grid = 16. If I change that to, say 50, and the grid-template-columns to 50, then it all works. But I can't figure out how to make that columns a variable.
const container = document.querySelector('.container');
let grid = 16;
function changeColor() { //Create the grid and div elements
for (i=0; i <= (grid * grid); i++) {
const grid = document.createElement('div');
grid.addEventListener('mouseover', colorBlack)
//Mouseover to black
container.appendChild(grid);
}
}
function colorBlack(e) { //Change color to black
e.target.classList.add('black');
}
function clearButton () { //Event listener for the clear button
let clear = document.getElementById('clear');
clear.addEventListener('click', removeColor)
}
function removeColor() { //Remove the black class from each div
let element = document.querySelectorAll('.black');
[].forEach.call(element, (e) => {
e.classList.remove('black');
})
}
changeColor();
clearButton();
I've tried defining the size in changeColor using a gridSize variable. But that just gives me a static number of columns and seems to add rows.
let gridSize = `${800/grid}px`;
for (i=1;i<=(grid*grid);i++){
let box = document.createElement('div');
box.setAttribute('id','box-style');
box.style.width = gridSize;
box.style.height = gridSize;
I was going to rebuild based on display: box instead of display: grid, but I've already got a functional grid with divs that change to black when hovered over.
I found an article and SO post about grid-columns variables.
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
But I can't seem to get it to function on the JS side. Is it even correct?
app.style.setProperty('--grid-rows', value)