Now, when you click #child, the console will show only: CHILD clicked, and #parent will not receive the event.
Forcing event capturing
By default, event listeners work in the bubbling phase, which means the event for #child will fire first, followed by the event for #parent. However, you can reverse this order by assigning the listener to the capturing phase, by passing true as the third argument to addEventListener.
Now #parent will fire before #child, because it handles the event during the capturing phase.
2. Event delegation
Event delegation is a technique of assigning an event listener to a parent element instead of attaching one to each child individually. It’s useful when elements are added to the DOM dynamically (e.g., via AJAX).
const newChild = document.createElement("div");
newChild.classList.add("child");
newChild.textContent = "New element";
document.getElementById("parent").appendChild(newChild);
We will still be able to detect clicks on the new element, even though we didn’t attach a separate addEventListener to it.
Author: Joanna
I write code that (usually) works. I tame WordPress, learn React, explore the world of DevOps, and click around in the Linux console. I optimize code as a hobby, because laziness is the purest form of productivity. I do my best not to lose my mind somewhere between a bug and a deadline.