Skip to content
Advertisement

Getting Javascript to accept button clicks

I am writing a program that is similar to an Etch-A-Sketch where moving the cursor over a block turns it from black to a random color. I want the user to be able to hold down the spacebar and the program will stop highlighting blocks, which will let the user move their cursor without messing up their drawing. I have tried line 10-25, but it does not do anything.

let flagVar = 0;
for(let i = 0; i < SQUARES; i++) {
  const square = document.createElement('div')
  square.classList.add('square')
  square.addEventListener('mouseover', () => setColor(square))
  square.addEventListener('button', () => removeColor(square))
  container.appendChild(square)
}

document.body.onkeydown = function(e){
  const square = document.createElement('div')
  if(e.keydown === 32){
    square.addEventListener('mouseout', () => removeColor(square))
    container.appendChild(square)
    flagVar++;
  }
}
document.body.onkeyup = function(e){
  const square = document.createElement('div')
  if(flagVar > 0 && e.keyup === 32){
    square.addEventListener('mouseover', () => setColor(square))
    container.appendChild(square)
    flagVar--;
  }
}

Edit: I have taken the code out of the for loop, and attempted to set a flag variable at the suggestion of IT goldman, but I am new to flag variables so I am unsure if I implemented this correctly. It still is not working

Advertisement

Answer

As It goldman pointed out, it’s better to set a flag to see if the cursor should paint or not, and as Barman also stated, use a single event listener. You can separate the squares apart by setting an unique id on each of them.

See this below as pseudo code.

let shouldPaint = true;

for (let i = 0; i < SQUARES; i++) {
  const square = document.createElement('div')
  square.classList.add('square')
  square.setAttribute('id', 'square' + i);

  container.appendChild(square)
}

setShouldPaint = (_shouldPaint, keyCode) => {
   const SPACE = 32;
   
   if (keyCode == SPACE) {
     shouldPaint = _shouldPaint;
   }
}

square.addEventListener('onkeydown', (event) => setShouldPaint(false, event.keydown))
square.addEventListener('onkeyup',   (event) => setShouldPaint(true, event.keyup))
square.addEventListener('mouseover', (event) => setColor(event.target.id, shouldPaint))
square.addEventListener('click',     (event) => removeColor(event.target.id))
Advertisement