I am currently working on creating a grid of boxes that can be clicked, sending notifications with their respective IDs to the server using SocketIO.
<body>
<div class="wrapper">
<div id="1" class="box"></div>
<div id="2" class="box"></div>
</div>
</body>
let boxes = document.querySelectorAll('.box');
Array.from(boxes, function(box) {
box.addEventListener('click', function() {
id = box.id
//Send socketio message to server
socket.emit('box_event_client', {data: id});
});
});
Although this method works and allows me to click on each box and send events to the server, I encountered an issue where the event listeners could not be removed. I found out from https://www.w3schools.com/jsref/met_element_removeeventlistener.asp
Note: To remove event handlers, the function specified with the addEventListener() method must be an external function, Anonymous functions, like "element.removeEventListener("event", function(){ myScript });" will not work.
To address this problem, I made some changes:
Array.from(boxes, function(box) {
box.addEventListener('click', addEL(box.id));
});
function addEL(boxID) {
console.log("Box clicked: " + boxID)
//Send socketio message to server
socket.emit('box', {data: boxID});
}
However, after loading the page into the browser, all boxes in the grid are automatically 'clicked' and events are sent to the server. Can someone provide insight into why this is happening?