I wrote an Etch-a-Sketch function via a for loop and tried to spice it up with a "clear" button to clear the divs and a "new" button to choose for a new grid. The clear() function only works the first time. From the second input on the bottom divs stay black if you choose a bigger grid resulting in displaying the "old" black divs in the new grid. I think that the clear() function has to be somehow implemented in the makeGrid() function, to clear the current grid, but how do I implement that in the eventListener? I hope you can understand what I mean, no native speaker here. here is the code, first HTML then Javascript.
<body>
<h2>Etch-a-sketch</h2>
<div class="btn-container">
<button type="button" id="btn">clear</button>
<button type="button" id="new">New</button>
</div>
<div class ="container" id="container">
</div>
</body>
document.addEventListener('DOMContentLoaded', () => {
function makeGrid(num) {
for(let i = 0;i < (num * num); i++) {
const div = document.createElement('div');
container.style.gridTemplateColumns = `repeat(${num}, 1fr)`;
container.style.gridTemplateRows = `repeat(${num}, 1fr)`;
container.appendChild(div).classList.add('gridItems')
div.addEventListener('mouseover', function(e){
e.target.style.backgroundColor = 'black';
})
}
}
function clear() {
gridItems.forEach(item => {
item.style.backgroundColor = 'pink';
});
}
let num = 0;
num = prompt('Pick a number between 1 and 100!');
if(num > 100){
prompt('to high!')
}else{
makeGrid(num);
}
function ask() {
let num = 0;
num = prompt('Pick a number between 1 and 100!');
if(num > 100){
prompt('to high!')
}else{
makeGrid(num);
}
}
const button = document.getElementById('btn');
const newBtn = document.getElementById("new");
const gridItems = document.querySelectorAll('.gridItems');
newBtn.addEventListener('click', ask);
button.addEventListener('click', clear);
})
Have a nice weekend and thank you!