Javier Correas
Javier Correas

Reputation: 91

Remove event listeners when user press 'space bar'

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

Upvotes: 2

Views: 775

Answers (2)

Tom Anderson
Tom Anderson

Reputation: 470

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.

Upvotes: 1

Sven.hig
Sven.hig

Reputation: 4519

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>

Upvotes: 0

Related Questions