Does event capturing go through siblings of the firing node?

981 views Asked by At

Say we have:

<div id="parent">d1
  <div id="child-1">child-1</div>
  <div id="child-2">child-2</div>
</div>

I have an event listener on child-2.

From what I understand, event capturing will go down the node tree until it reaches the node the event fired.

Does event capturing also go through the sibling children, checking if they are the target that fired the event?

1

There are 1 answers

0
KeyvanKh On

As you can see in this snippet if click on child1 first parent then child1 fires. if you check the console you'll see that both e.target are the same, so the event will target the same element on parent and child. when clicking the child1 : event goes from parent to child1 and child2 event never fire up

const parent= document.getElementById('parent');

const child1 = document.getElementById('child1');
const child2 = document.getElementById('child2');

parent.addEventListener(
  'click',
  e => {
  console.log("parent")
  console.log(e.target)
  },
  true
);

child1.addEventListener(
  'click',
  e => {
    console.log("child1")
    console.log(e.target);
  },
  true
);

child2.addEventListener(
  'click',
  e => {
    console.log("child2")
    console.log(e.target);
  },
  true
);
.parent{
width: 500px;
height: 500px;
background-color: orange;

}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Expense Tracker</title>
  </head>
  <body>
    <h1>Event Capturing</h1>
    <div class="parent" id="parent">
      <h2 id="child1">Child1</h2>
      <h3 id="child2">Child2</h3>
    
    </div>
  </body>
</html>