What is event bubbling and event delegation?

Event Bubbling

Event bubbling is a type of event propagation in the DOM where an event starts at the most specific (innermost) target element and bubbles up to the least specific (outermost) ancestor element. This means that the event is first handled by the element that triggered it, and then successively handled by its parent elements up the DOM tree until it reaches the window object.

Example of Event Bubbling

<div>
  <button class="child">Hello</button>
</div>
<script>  

const parent = document.querySelector("div");

const child = document.querySelector(".child");

parent.addEventListener("click", function () {

console.log("Parent");

});

child.addEventListener("click", function () {

console.log("Child");

});

</script>

Output:

Child

Parent


#### **Key Points:**
- **Propagation Order:** The event is first handled by the target element, then by its ancestors in the DOM hierarchy.
- **Default Behavior:** Most events in the DOM bubble by default unless specifically stopped.
### Event Delegation

Event delegation is a technique used to handle events at a higher level in the DOM rather than on individual elements. It involves setting up a single event listener on a parent element that handles events for all of its child elements. This technique is particularly useful when dealing with dynamically added elements or when there are many similar elements.

Example of Event Delegation

<form id="registration-form">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
</form>

<script>
var form = document.querySelector("#registration-form");

// Listen for changes to fields inside the form
form.addEventListener("input", function (event) {
// Log the field that was changed
console.log(event.target);
}, false);
</script>


Key Points:

  • Single Event Listener: Only one event listener is needed on the parent element to manage events for all child elements.
  • Dynamic Elements: It works well with elements that are added or removed dynamically.
  • Performance: Reduces the number of event listeners and improves performance by consolidating event handling.


Additional Information

  • Event Bubbling vs. Capturing: Event bubbling is one phase of event propagation; the other is capturing, where the event starts from the outermost element and propagates inward.
  • Stopping Propagation: Both bubbling and capturing can be stopped using event.stopPropagation() if you need to prevent the event from reaching further up or down the DOM tree.
  • Advantages of Event Delegation: Simplifies event management, especially in cases with many child elements or dynamic content.