Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Event Listener "click" shows the "body" element instead of the element that I clicked on?

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 class="square-55d63 white-1e1d7 square-e2" 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="" class="piece-417db" data-piece="wP" style="width:49px;height:49px;"></div>").

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
  class="square-55d63 black-3c85d square-g7"
  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]"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading