I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious.
JS
const gridContainer = document.getElementById('container');
function makeGrid(rows, cols) {
gridContainer.style.setProperty('--grid-rows', rows);
gridContainer.style.setProperty('--grid-cols', cols);
for (i = 0; i < rows * cols; i++) {
let cell = document.createElement('div');
gridContainer.appendChild(cell).className = 'grid-item';
}
}
makeGrid(16, 16);
const gridElement = document.getElementById('grid-item');
gridElement.addEventListener('click', () => {
gridElement.target.style.backgroundColor = 'white';
})
CSS
:root {
--grid-cols: 1;
--grid-rows: 1;
}
#container{
display: grid;
grid-gap: 0em;
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
background-color: black;
}
.grid-item{
padding: 1em;
border: 1px solid #131313;
text-align: center;
}
.grid-item:hover{
background-color: #ddd;
}
const gridContainer = document.getElementById('container');
function makeGrid(rows, cols) {
gridContainer.style.setProperty('--grid-rows', rows);
gridContainer.style.setProperty('--grid-cols', cols);
for (i = 0; i < rows * cols; i++) {
let cell = document.createElement('div');
gridContainer.appendChild(cell).className = 'grid-item';
}
}
makeGrid(16, 16);
const gridElement = document.getElementById('grid-item');
gridElement.addEventListener('click', () => {
gridElement.target.style.backgroundColor = 'white';
})
:root {
--grid-cols: 1;
--grid-rows: 1;
}
#container {
display: grid;
grid-gap: 0em;
grid-template-rows: repeat(var(--grid-rows), 1fr);
grid-template-columns: repeat(var(--grid-cols), 1fr);
background-color: black;
}
.grid-item {
padding: 1em;
border: 1px solid #131313;
text-align: center;
}
.grid-item:hover {
background-color: #ddd;
}
<div id="container"></div>
I attempted to create a separate function to target and change the color of the grid element upon clicking, but it does not respond to clicks as expected.