Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

468
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!