2

I need to remove all event listeners when the user presses the space bar and get them back when press again the press bar or any key. How can I achieve it? My event listeners:

function makeRows(rows, cols) {
  container.style.setProperty('--grid-rows', rows);
  container.style.setProperty('--grid-cols', cols);
  container.style.border = '3px solid #0000FF'
  for (c = 0; c < (rows * cols); c++) {
    let cell = document.createElement("div");
    container.appendChild(cell).className = "grid-item";
    cell.addEventListener("mouseover", paint);
  };
};

EDIT: I have tried this to remove the event listeners:

document.addEventListener("keypress", function(){
  const grid = document.getElementsByClassName('grid-item');
  Array.from(grid).forEach((el) => {
    el.removeEventListener("mouseover", paint);  
  });
});

But now I do not know how to get them back when the user presses a key again...

Thanks in advance

  • Honeslt its unclear, what you are trying to achieve... Could you please elaborarte what you want to achieve instead of what you are trying to do? – Rajesh Jul 27 '20 at 05:51
  • 2
    To remove event listeners see this [similar post](https://stackoverflow.com/questions/4386300/javascript-dom-how-to-remove-all-events-of-a-dom-object). – Tanner Dolby Jul 27 '20 at 05:51
  • 1
    Bind an event listener that checks for the press of the `Space` key, set or unset a global state, and use an `if` statement inside `paint` (or whichever event listener you like). Have you tried something like this? – Sebastian Simon Jul 27 '20 at 05:53

2 Answers2

1

You can use removeEventListener to remove event listeners from an element. Pass it the event (eg mouseover) and the callback for it (eg paint), and it will remove that handler for that event from that element.

It is important to note that removeEventListener only works with named functions, so if you declare an anonymous function as the handler (using () => {...} for example), then it won't work.

To use this in your example, you could have an array of event/listener pairs, which can be iterated through to add and remove as you need. Finally, ad another listener for the space key, which will handle the toggling in it's own callback. Since you have the list of events and callbacks that you will be adding and removing, it will remain untouched.

Tom Anderson
  • 440
  • 3
  • 10
0

Here is an example of how to remove and activate event listener with space bar

dv=document.getElementById("dv")
f=false
dv.addEventListener("click",log)
function log(){
console.log("clicked")
}
document.body.addEventListener("keydown",stoplog)
function stoplog(e){
  if(e.keyCode == 32&& f==false){
   dv.removeEventListener("click",log)
   f=true
}
 else dv.addEventListener("click",log) ,f=false

}
<div id="dv">click</div>
Sven.hig
  • 4,449
  • 2
  • 8
  • 18