I am creating a etch-a-sketch game. Now, the grid cells change to black when i hover mouse. I want to turn every cell to white when i press reset button.I tried creating an event Listener to button and giving a function to change for background of cells.It didn’t work.
Thank you.
JavaScript
x
49
49
1
const container = document.getElementById('container');
2
3
4
5
//div for buttons
6
const buttonDiv = document.createElement('div');
7
buttonDiv.classList.add('button-div');
8
container.appendChild(buttonDiv);
9
10
//A button to reset Everything
11
const resetButton = document.createElement('button');
12
resetButton.textContent = 'Reset';
13
buttonDiv.appendChild(resetButton);
14
15
//grid in a seperate div
16
const grid = document.createElement('div');
17
grid.classList.add('grid');
18
container.appendChild(grid);
19
20
//function to create grid
21
function makeGrid(value){
22
grid.style.gridTemplateColumns = `repeat(${value}, 30px)`;
23
grid.style.gridTemplateRows = `repeat(${value}, 30px)`;
24
for(let i = 0; i < value; i++){
25
for(let j = 0; j < value; j++){
26
const cell = document.createElement('div');
27
cell.backgroundColor = 'white';
28
cell.setAttribute('style','border: 1px solid #000000');
29
cell.addEventListener('mouseover', toBlack);
30
grid.appendChild(cell);
31
}
32
}
33
}
34
35
36
//to change the cell color to black on mouseover
37
function toBlack(e){
38
e.target.style.backgroundColor = 'black';
39
}
40
41
function resetGrid(){
42
const value = prompt('Input a number of Squares');
43
makeGrid(value);
44
}
45
46
resetButton.addEventListener('click',resetGrid);
47
48
window.onload = () => {makeGrid(16)};
49
Advertisement
Answer
You could just set the grids innerHTML to an empty string.
JavaScript
1
6
1
function resetGrid() {
2
const value = prompt('Input a number of Squares');
3
grid.innerHTML = '';
4
makeGrid(value);
5
}
6