I'm drawing a grid of boxes, want to be able to click on each box and send notification with its ID to 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});
});
});
This works, I can click each box and event is sent to server, but apparently this does not allow the even listener to be removed, as per 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.
So I changed to this
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});
}
Now as soon page is loaded into browser all boxes in grid are automatically 'clicked' and events sent to server.
Can anyone help understand why this is happening?