I am trying to make the cells on a 5×5 grid change to a random color when clicked on. I am having problems getting them to change when clicked. I am unsure of how to make a non button clickable and unsure about how to target multiple id’s in one statement vs doing it 25 times. I tried with jsut the first square to test it out and could link it correctly. I tried to get element by the first id and add event listener with click and change color function. I am almost positive that is my problem. When I do this my entire grid disappears.
html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>YOUR title here</title>
<meta name="description" content="brief description of YOUR page here">
<meta name="keywords" content="keywords related to YOUR page here">
<meta name="author" content= "YOUR name here">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="grid.js" defer></script>
<link rel="stylesheet" href="grid.css"/>
</head>
<body>
<div class="grid_container"></div>
<div>
<button id="reset">Reset Grid</button>
</div>
</body>
</html>
………………………………………………………………………………………….
JavaScript
//linking elements to the script
document.getElementById('reset').addEventListener('click', reset);
document.getElementById('sqr0').addEventListener('click', change_color);
//function to create the grid cells
function create_grid(rows, cols){
const grid_container = document.getElementsByClassName('grid_container')[0];
for (let i = 0; i < rows; i++){
for(let j = 0; j < cols; j++){
const square = document.createElement('div');
square.classList.add('square');
grid_container.appendChild(square);
}
}
}
create_grid(5,5);
//function to assign unique id's to each square
function id(){
//targeting the grid div element, then the squares
const grid_div = document.querySelector('.grid_container');
const grid_cell = grid_div.querySelectorAll('.square');
//loop to create a unique id on each square
for (let i = 0; i < grid_cell.length; i++)
grid_cell[i].id = "sqr" + i;
}
id();
//function to reset
//just refreshing the entire page
function reset() {
location.reload();
}
//function to generate a random color
//used https://css-tricks.com/ to help with generating random color
function get_random_color(){
let random_color = math.floor(math.random()*16777215).tostring(16);
return;
}
//function to change the background to a random color
function change_color(){
element.style.backgroundColor = get_random_color();
}
......................................................................................................
css
/*making the grid container*/
.grid_container {
display: grid;
grid-template-columns: repeat(5, 50px);
grid-template-rows: repeat(5, 50px);
gap: 1px;
}
.square {
aspect-ratio: 1;
border: 1px solid black;
background-color: white;
}