In JavaScript, event propagation can occur in two models: event bubbling and event capturing. Let’s explore how these models work and how they can be applied to your code.

Let’s say you have the following DOM structure:

<div id="container">
  <button>Click me</button>
</div>

You want to track when users click on the button, and you have two event listeners - one on the button itself and one on the #container element.

Before we dive into the details, it’s important to note that by default, all events bubble. This means that when a child element triggers an event, the event will propagate to its parent elements, unless propagation is explicitly stopped.

In the case of event bubbling, the event starts from the clicked item (the child) and propagates up the parent tree, starting from the nearest parent. In our example, the event handler on the button will fire before the handler on the #container element.

On the other hand, event capturing follows the opposite order. The outer event handlers are fired first, followed by the more specific handler on the button.

To apply event capturing, you can use the addEventListener method and set the third argument to true:

document.getElementById('container').addEventListener(
  'click',
  () => {
    // Code to execute when the event occurs
  },
  true
);

When event capturing is used, all capturing event handlers are run first, followed by the bubbling event handlers. The order of execution follows a specific principle: the DOM starts from the Window object, traverses all elements, and looks for the target element that triggered the event. As it does so, it calls any event handlers associated with the event in the capturing phase. Once the target element is reached, the DOM then repeats the journey up the parent tree until it reaches the Window object again, calling the event handlers in the bubbling phase.

Understanding event bubbling and event capturing can help you control how events propagate in your JavaScript code. By leveraging these concepts, you can create more robust and efficient event handling mechanisms.