# 16) Event Propagation and Delegation

1.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Event Delegation</mark>**  
    Event delegation is a technique used in JavaScript to handle events efficiently, especially in cases where you have a large number of elements that may trigger the same event. Instead of attaching an event listener to each individual element, you attach a single **event listener** to a **parent element** that contains all the elements you're interested in. Then, you use **event bubbling** or **capturing** to catch events as they **propagate up or down** the DOM tree.  
    Here's how event delegation works,  
    **i) Select a common parent element**  
    Choose a parent element that contains all the child elements you want to monitor for events. This could be the `document` itself, or a specific container element.  
    **ii) Attach an event listener to the parent**  
    Use `addEventListener` to attach an event listener to the parent element.  
    **iii)** **Determine the target element**  
    When the event occurs, it bubbles up or down the DOM tree. You can determine the target element that triggered the event using the [`event.target`](http://event.target) property.  
    **iv)** **Check if the target is of interest**  
    Inside the event handler, you can check if the event target matches the elements you're interested in. If it does, you can execute the desired code.  
    Here's a simple example of event delegation using JavaScript,
    
    ```html
     <!DOCTYPE html>
     <html lang="en">
     <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Event Delegation Example</title>
     </head>
     <body>
    
     <div id="parent">
       <button class="btn">Button 1</button>
       <button class="btn">Button 2</button>
       <button class="btn">Button 3</button>
     </div>
    
     <script>
     document.getElementById('parent').addEventListener('click', function(event) {
       // Check if the clicked element is a button
       if (event.target.classList.contains('btn')) {
         // Execute the desired code
         alert('Button clicked: ' + event.target.textContent);
       }
     });
     </script>
     </body>
     </html>
    ```
    
    In this example, we attach a click event listener to the parent `<div>` element with the id `parent`.  
    When any element inside the parent is clicked, the event bubbles up to the parent, triggering the event handler. We then check if the clicked element has the class `btn` (which is the class of the buttons inside the parent).  
    If it does, we execute the code to show an alert with the text content of the clicked button.  
    This way, we only need one event listener for all the buttons, which improves performance and reduces code complexity.
    
2.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Event Propagation</mark>**  
    Event propagation in the Document Object Model (DOM) refers to the mechanism by which events are handled and passed through the DOM tree. There are two main phases of event propagation: capturing phase and bubbling phase.  
    **i)** **Capturing Phase**  
    During this phase, the event is captured from the outermost ancestor down to the target element. This means that the event starts at the root of the DOM tree and moves towards the target element. Any event listeners attached during the capturing phase will be triggered at this stage.  
    **ii) Target Phase**  
    Once the event reaches the target element, the target phase begins. Event listeners attached directly to the target element are triggered.  
    **iii) Bubbling Phase**  
    After the target phase, the event bubbles up from the target element back to the outermost ancestor. This means that the event travels from the target element up to the root of the DOM tree. Any event listeners attached during the bubbling phase will be triggered at this stage.  
    Event propagation can be influenced by the `addEventListener()` method in JavaScript. By default, event listeners are attached in the bubbling phase. However, you can specify `true` as the third parameter to attach the event listener during the capturing phase:
    
    ```javascript
     element.addEventListener(eventType, listener, useCapture);
    ```
    
    `eventType`: The type of event to listen for (e.g., "click", "mouseover").  
    `listener`: The function to execute when the event occurs.  
    `useCapture`: Optional. A boolean value indicating whether to use the capturing phase (`true`) or the bubbling phase (`false`, default).
    
3.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Bubbling and Capturing</mark>**  
    Bubbling and capturing are two different mechanisms of event propagation in the Document Object Model (DOM),  
    **i)** **Capturing**  
    In the capturing phase, the event is first captured by the **outermost ancestor** element and then propagated **downwards** through its descendants until it reaches the **target element**. Event listeners attached during this phase will trigger in the order of ancestors towards descendants. Capturing is less commonly used but can be useful in scenarios where you want to intercept events at an early stage of propagation.  
    **ii)** **Bubbling**  
    In the bubbling phase, the event is first triggered on the **target element** and then propagated upwards through its ancestors until it reaches the **root of the DOM tree**. Event listeners attached during this phase will trigger in the order of descendants towards ancestors. Bubbling is the default behavior for most events in the DOM.  
    The main difference between capturing and bubbling in the DOM lies in the direction of event propagation:  
    **i) Capturing**  
    In capturing, the event is first captured at the outermost ancestor element and then propagates inward towards the **target element**. It starts from the root of the DOM tree and moves towards the target element.  
    **ii)** **Bubbling**  
    In bubbling, the event is first triggered on the target element and then propagates outward through its ancestors towards the root of the DOM tree. It starts from the target element and moves towards the root.
    
    Here's a summary of the differences,  
    i) **Direction**  
    Capturing goes from the **outermost ancestor towards the target**, while bubbling goes from the **target towards the outermost ancestor**.  
    ii) **Order of Execution**  
    In capturing, event handlers attached at higher-level elements trigger before those at lower-level elements. In bubbling, it's the opposite: handlers at lower-level elements trigger before those at higher-level elements.  
    iii) **Default Behavior**  
    Bubbling is the default event propagation mechanism in most browsers. Capturing is less commonly used but can be invoked explicitly by setting the `useCapture` parameter to `true` in the `addEventListener()` method.
    
    ![](https://cdn.hashnode.com/uploads/covers/65d60707e8ef919f4abfc8f5/f2a5e88b-fbb2-4314-8e63-4abdb4c219fa.png align="center")
