Is there a way to eliminate numerous event listeners from a specific group of elements?

There's a situation with my button elements where I want them to stop being clickable once a certain condition is met. I thought using the removeEventListener function would work, but even after my if statement evaluates to true, the buttons remain interactive.

const field = Array.from(document.querySelectorAll(".field"))
    const boardData = [];
    
    field.forEach(button => {
        
        const func = (e) => {


            
            if(xTurn) {
                if(checkWin(player1)){
                    freezeBoard(field,func)
                };
            }
            
            else  {                                           
                if(checkWin(player2)){
                    freezeBoard(field,func)                        
                };
            }
        }
        button.addEventListener("click", func)
        
    })
    function freezeBoard(buttons,func) {
        buttons.forEach(button => {

            button.removeEventListener("click", func);           
        })
    }

Answer №1

Ensure that the func is declared outside to have only one instance of it - if created inside a loop, each listener will use a different reference, causing issues with removeEventListener.

const buttons = Array.from(document.querySelectorAll(".field"))
const boardData = [];
const func = () => {
    if ((xTurn && checkWin(player1) || checkWin(player2))) {
        freezeBoard(field, func);
    }
};
buttons.forEach(button => {
    button.addEventListener("click", func)
});
function freezeBoard(buttons) {
    buttons.forEach(button => {
        button.removeEventListener("click", func);
    })
}

You can simplify further by eliminating arguments and condensing the condition for better readability.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing an object's attribute to reference an image for a source

I am encountering an issue trying to display an image from the video object's image attribute on the screen when my program runs. The problem lies in the fact that there is no file named 'videoObj1.image', which causes a source error. I am e ...

Enhance text by hovering over it

I am currently working on implementing a unique feature using jQuery and CSS. Rather than just inheriting the width, I want to create a magic line that extends to the next index item. Scenario: 1: Hover over Element one ELEMENT ONE ELEMENT TWO ELEM ...

Issues with Bootstrap's "img-fluid" class functionality

I recently started the web development course by Colt Steele and ran into an issue while working on the "Museum of Candy project" (I made some modifications to it). The problem is that I am using a widescreen monitor, and when I expand my window, the image ...

Implementing One Time Events in C# (Firing only once)

I'm interested in developing an event handling object that allows subscription for one-time execution only, followed by automatic unsubscription. Is there a similar native functionality in .NET? Currently, this is what works for me: public class Cus ...

The mousedown event handler in Three.js disrupts the focus on the input field

Here is a line of code in threejs: document.addEventListener('mousedown', onDocumentMouseDown, false); This particular code snippet causes the input field to lose focus when clicked. This can be problematic, for instance, when there is a canva ...

Display an XML or TXT file in a web browser using JavaScript

Looking for a solution to print an XML or TXT file directly from your browser? I have a thermal printer and I'm struggling with formatting issues when printing from the browser using javascript. The browser tends to mess up the file, making it unrecog ...

Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below. var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?"; $.getJSON(jsonUrl,function(zippy){ ...some code } However, I want to pass a ...

Utilizing external functions in Node.js by importing them from different files

Struggling to import methods from my ./db/index.js into my server.js file in order to retrieve data from the database and show it. The content of /db/index.js is as follows: 'use strict'; const pgp = require('pg-promise')(); const pg ...

Adjusting the dimensions of :before with JavaScript: A Step-by-Step Guide

There's this CSS3 tag named body:before that I'm working with, and I'm looking to adjust the height and width of body:before using JavaScript. Any suggestions on how to achieve this? ...

Here are the steps to calculate the duration between two dates in the specified format:

let d1 = new Date("05/20/2022 09:28:15") let d2 = new Date("05/24/2022 12:38:25") Can someone help me calculate the difference between these two dates? ...

How to utilize Vue.js for making a GET request by including an ID as a path parameter

My goal is to make a GET request to my backend application and pass an ID as a query parameter. The endpoint I want to use is - GET /api/v1/imports/products_batches/:id. Below is the code I have written: imports.js const fetchSyncedProductsResultReques ...

Using a Jquery selector with either the ID Regex or a repetitive class

There is a collection of similar elements with matching IDs Below are two methods for selecting them using Jquery: Select by ID + Regex (For example, How can I select an element by ID with jQuery using regex?) Add a redundant class to all the elemen ...

Use CSS to position the SVG element to the bottom right corner of the screen

I have a <div> on the page with the CSS class .svgImage applied to it. Whenever I resize the browser window, the svg image resizes correctly but keeps shifting its position on the page. When I make the browser window vertically smaller, the svg imag ...

Create a variable that holds the response from the requestjs assignment

Is there a way to store the body of request.get('http://someurl/file.json', function(err, response, body) {}) in a variable? Consider this example: file.json { "Name1": { "prop": "value" }, "Name2": { "prop": "value ...

Stopping PHP execution when an Ajax request is aborted

I want the browser to wait for notifications, but stop waiting if a link is clicked. To achieve this, I have created a PHP script with a while loop that ends when an event occurs and then returns that event. PHP require 'required.php'; ignore_ ...

Issues with debuggers in Chrome and Firefox with AngularJS are causing frustration for developers

Currently, I am in the process of developing a hybrid application that combines AngularJS with Angular 8. As part of my testing procedure, I am attempting to debug the application. However, I have encountered an issue where the debuggers function properly ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Deactivate a Button until Another One is Clicked in React

Is there a way to disable the submit button until a rating has been provided? My Current State this.state = { stars: [ { active: false }, { active: false }, { active: false }, { active: false }, { active: fal ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

React Login Redirect

I am struggling to implement a redirect in my React project login. Despite researching online and finding solutions using routers, I have been unsuccessful in adding it to my code correctly. Here is my code - how can I effectively implement the router? Ap ...