Help with removeEventListener

So for my Tic Tac Toe project I’ve used

const spaces = document.querySelectorAll('.col');

spaces.forEach(function(input){ 
   input.addEventListener('click', function playMove() {
     //code  
   })
})

is there a way to remove that listener from within ? I’m having a real brain frazzled day D:

edit: Im able to remove from the last square clicked, but not for all

Something like this?

const box = document.querySelector(".box");

box.addEventListener("mouseover", function callback() {
  alert("Hi!");
  box.removeEventListener("mouseover", callback);
});

Yes this works for single elements and I can use the same idea to remove the event listener from the last space clicked. But as Im using forEach it wont target all the spaces :frowning:

Works for me.
https://codepen.io/Implaier/pen/MOMWmM

Update:
I see what the problem was first solution doesn’t’ work.

Here’s another try.
https://codepen.io/Implaier/pen/NwZWXe

Edit:
To remove a listener the signature must be the same, and the callback function used inside of addEventListener must exist to be referenced later on inside removeEventListener.

Hmm I suppose I could have been clearer, I think its best I just share all the code, as I believe your solution wont work for me,

I want it so after a game has been won squares cant be clicked :thinking:
The forEach method is getting information from the data of the element that is being clicked. I think I need to go sit down and do something different cause my brain is all fog D:

Try adding a flag like this.
https://codepen.io/Implaier/pen/eewzQp

let gameWon = false;
...
input.addEventListener('click', function playMove() {
	if (gameWon) return;
	...
	...
	if(isGameWon()){
			gameWon = true;
	...
	}
}
1 Like

Yeah it crossed my mind while I was out haha! You wont believe how hard im kicking myself right now :rofl: cheers man @Implaier sometimes you just need that outside view

1 Like