Skip to content
Advertisement

How to reset black colored grid to white by clicking reset button?

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.

const container = document.getElementById('container');



//div for buttons
const buttonDiv = document.createElement('div');
buttonDiv.classList.add('button-div');
container.appendChild(buttonDiv);

//A button to reset Everything
const resetButton = document.createElement('button');
resetButton.textContent = 'Reset';
buttonDiv.appendChild(resetButton);

//grid in a seperate div
const grid = document.createElement('div');
grid.classList.add('grid');
container.appendChild(grid);

//function to create grid
function makeGrid(value){
    grid.style.gridTemplateColumns = `repeat(${value}, 30px)`;
    grid.style.gridTemplateRows = `repeat(${value}, 30px)`;
    for(let i = 0; i < value; i++){
        for(let j = 0; j < value; j++){
        const cell = document.createElement('div');
        cell.backgroundColor = 'white';
        cell.setAttribute('style','border: 1px solid #000000');
        cell.addEventListener('mouseover', toBlack);
        grid.appendChild(cell);
        }
    }
}


//to change the cell color to black on mouseover
function toBlack(e){
    e.target.style.backgroundColor = 'black';
}

function resetGrid(){
    const value = prompt('Input a number of Squares');
    makeGrid(value);
}

resetButton.addEventListener('click',resetGrid);

window.onload = () => {makeGrid(16)};

Advertisement

Answer

You could just set the grids innerHTML to an empty string.

function resetGrid() {
  const value = prompt('Input a number of Squares');
  grid.innerHTML = '';
  makeGrid(value);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement