Event propagation illustration
by Julien Roche
HTML
<div class="parent" id="first-parent">
<div class="child" id="first-child">First element</div>
</div>
<div class="parent" id="second-parent">
<div class="child" id="second-child">Second element</div>
</div>
<div class="parent" id="third-parent">
<div class="child" id="third-child">Thired element</div>
</div>
<div class="parent" id="fourth-parent">
<div class="child" id="fourth-child">Fourth element</div>
</div>
CSS
.parent {
background-color: grey;
border: 1px solid black;
display: flex;
justify-content: center;
margin: 1rem 1rem 1rem 1rem;
padding: 1rem 1rem 1rem 1rem;
}
.child {
align-items: center;
background-color: white;
border: 1px solid white;
color: black;
display: flex;
height: 3rem;
justify-content: center;
width: 20rem;
}
Babel + JSX
function parentHandler() {
alert('Parent hanlder called');
}
function childHandler() {
alert('Child hanlder called');
}
document.querySelector('#first-child').addEventListener('click', childHandler, false);
document.querySelector('#first-parent').addEventListener('click', parentHandler, false);
document.querySelector('#second-parent').addEventListener('click', parentHandler, false);
document.querySelector('#second-child').addEventListener('click', childHandler, true);
document.querySelector('#third-child').addEventListener('click', childHandler, false);
document.querySelector('#third-parent').addEventListener('click', parentHandler, true);
document.querySelector('#fourth-child').addEventListener('click', childHandler, true);
document.querySelector('#fourth-parent').addEventListener('click', parentHandler, true);
// Scenario description:
// Case 1: useCapture for parent and child both false => child will be called first (even if listener declared before child!)
// Case 2: useCapture for parent to false and child to true => child will be called first (even if listener declared before child!)
// Case 3: useCapture for parent to true and child to false => parent will be called first (even if listener declared after child!)
// Case 4: useCapture for parent and child both true => parent will be called first (even if listener declared after child!)