Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

464
Visualizações
Clear Button in Etch-a-Sketch only works once

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!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda