Home > Back-end >  Why Event Listener "click" shows the "body" element instead of the element that
Why Event Listener "click" shows the "body" element instead of the element that

Time:01-08

I went to chessboard.js https://chessboardjs.com/examples#5000 , opened Developer Tools and pasted the following code

document.body.addEventListener(`click`, a1);
function a1(){
   console.dir(event.target);
}

When I clicked on an empty chess square or on a square with a black piece, the console printed the correct result (for example, "div#e5-b9f9-a5bc-69e1-3e5a-4b82-b2bc-ffe4-966c.square-55d63.black-3c85d.square-e5").

But when I clicked on a square with a white piece on it, the console printed "body". When I right-clicked on the same square and chose "Inspect" it correctly showed an "img" element inside a "div" element in the section "Elements" of the Developer Tools (for example, <div style="width:49px;height:49px;" id="e2-f699-d489-4d29-2e6f-2a64-c1ec-e26f-fb62" data-square="e2"><img src="chessboard/img/chesspieces/wikipedia/wP.png" alt="" data-piece="wP" style="width:49px;height:49px;"></div>").

What is the reason for showing "body" instead of a correct element? What should I do to make the program show me the element I clicked on?

CodePudding user response:

Don't just use event.target on itself unless you really know what you're doing. Usually it goes in combination with .closest() which is 99% when it should be used - and that's exactly what you also need.

Also, instead of assigning event to body, use a nearest ancestor like #myBoard

Also, use "mousedown" Event - since it seems like the "click" hangs because the element never receives a "mouseup" to fulfill the "click" since the cell is manipulated programmatically

function cellClick (evt){
   const elCell = evt.target.closest("[data-square]");
   if (!elCell) return; // Do nothing. No cell element.

   // Otherwise do...
   console.dir(elCell);
}

document.querySelector("#myBoard").addEventListener(`mousedown`, cellClick);

Since the cell elements you want to target use a dataset Attribute, i.e:

<div
  
  id="g7-06f7-5132-52ee-91f2-0b5b-ab5a-4157-7f9c"
  data-square="g7"
>...</div>

and since that attribute is used for all cells I used the Attribute selector "[data-square]"

  • Related