I am currently developing a basic etch-a-sketch program with two buttons. One button resets the screen, while the other creates a new screen where you can specify the number of pixels in the drawing area. The default size and reset functions are working properly. However, when I click the new button to set the number of pixels, the event listener stops functioning correctly, resulting in the mouseover effect not changing the background color of the divs anymore. Below is the code snippet:
const screen = document.querySelector('.screen')
const clearButton = document.querySelector('.clear-btn');
const newButton = document.querySelector('.new-btn');
var size = 64;
function createGrid(size) {
document.styleSheets[0].cssRules[3].style["grid-template-columns"] = "repeat(" + size + ", 1fr)"
document.styleSheets[0].cssRules[3].style["grid-template-rows"] = "repeat(" + size + ", 1fr)"
console.log('createGrid');
for (i = 0; i < size*size; i++) {
const grid = document.createElement('div');
grid.classList.add('grid');
grid.style.cssText = 'color: #cccccc; background: #cccccc; border: solid 1px lightgrey;';
screen.appendChild(grid);
}
}
function reset() {
var grid = document.getElementsByClassName('grid');
Array.from(grid).forEach((tile) => {
tile.style.backgroundColor = "#cccccc";
});
}
function newSize(){
let userResponse = prompt("Please enter size of canvas: ", "");
size = parseInt(userResponse);
remove();
createGrid(size);
}
function remove(){
while (screen.firstChild) {
console.log(size);
screen.removeChild(screen.firstChild);
}
}
createGrid(size);
clearButton.addEventListener('click', reset);
newButton.addEventListener('click', newSize);