I am creating a tic-tac-toe game where I add event listeners to check if a box is clicked. Here is the function I am using to add click events to elements on my page:
function addClickEvents(){ for (let i = 0; i < images.length; i++) { boxes[i].addEventListener( "click", function () { addEvents(i); }, { once: true } ); } } function addEvents(x) { document.images[x].style.display = "block"; }
I would like to remove these events so I don’t overlap them once the game is reset. I have a separate button on the page that resets the game. Is there anyway to remove the eventListeners using that button? I have used a function that looks like this but it does not seem to work:
function resetGame() { for (let reset = 0; reset < 9; reset++) { document.boxes[reset].removeEventListener("click", addEvents); } }
I have also tried to attach the function to a variable and add it that way, but this does not work as far as i know since I need to pass a variable into the function.
Advertisement
Answer
You can try adding a common class to your boxes elements and then use them later in the code to remove the event listeners.
First you will add class like:
function addClickEvents(){ for (let i = 0; i < images.length; i++) { boxes[i].classList.add('boxes');// add class to the boxes boxes[i].addEventListener( "click", function () { addEvents(i); }, { once: true } ); } }
Then you can write reset function like:
function resetGame() { document.querySelectorAll('.boxes').forEach((box)=>{ box.outerHTML = box.outerHTML;// This will remove all event listeners }) }
For more information you can look at this answer