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>