0

I thought I understood javascript event propagation. But apparently not. I would like the container to capture the click event without its descendants receiving it. The third parameter of addEventListener does not change the behavior of the event.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  </head>
  <body>
    <div id="container" style="padding: 10px; border: 1px solid black;">
      <div id="child1" style="margin: 10px; background-color: chartreuse;">
        child1 content
      </div>
      <div id="child2" style="margin: 10px; background-color: aqua;">
        child2 content
      </div>
    </div>
    <script>
      document.getElementById("container").addEventListener('click', (e) => {
        console.log(e);
      }, false) // true don't change behavior
    </script>
  </body>
</html>

If click on child, the event target is child and never container. The event is neither captured by container nor escalated by child. Any idea ?

The solution i wrote works but seems very heavy.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
  </head>
  <body>
    <div id="container" style="padding: 10px; border: 1px solid black;">
      <div id="child1" style="margin: 10px; background-color: chartreuse;">
        child1 content
      </div>
      <div id="child2" style="margin: 10px; background-color: aqua;">
        child2 content
      </div>
    </div>
    <script>
      document.getElementById("container").addEventListener('click', (e) => {
        if (e.target.getAttribute('id') == 'container') {
          console.log('ok');
        }
        else {
          console.log('ko');
          !e.target.parentElement.dispatchEvent(new MouseEvent("click"));
        }
      }, false)
    </script>
  </body>
</html>
  • Have you tried this? https://stackoverflow.com/questions/23597480/trigger-click-on-child-but-prevent-event-propagation-to-parent Look into the stopPropagation function – James Donaldson Jun 11 '23 at 14:09
  • Use `e.currentTarget` to get the element that the listener was added to, not the child you clicked on. – Barmar Jun 11 '23 at 14:19

1 Answers1

0

There are several methods to prevent this, using javascript or css:

Using javascript, you can check if currentTarget is not the target then we know it's a decendant. You can also use currentTarget to always get the parent container.

if(e.target !== e.currentTarget) return;

Or with css you can use pointer-events: none; on any child you don't want to receive the click event.

rhld16
  • 1
  • 2