To understand event delegation in javascript, let have a scenario where we following DOM.
I am sure you must be wondering what happens when you click on button 1. what gets logged to console and how does that works ........ I will encourage you to try it out and then get back to the blog ( otherwise one butterfly dies).
execution of events in above case is pretty trivial and intutive , the innermost event gets fired first and outermost at the end i.e, Button ---> Container ---> Main ---> Document
To understand this behavior we need to understand how event propagates in javascript
Event propagation
Event in javascript has two phase (excluding target : ) )
Capturing phase : the events in dom starts from the window and travels down the DOM tree until it reaches the event origin i.e, event.target
Bubbling phase : once the event has reached the target, it starts to bubble up while executing the event handlers along the way. i.e, in above case the it will first execute the button handler, then will move up the hierarchy.
How to execute events in capturing phase ?
You can mark this behavior of the event while adding them to the DOM by making the property capture as true, this will tell javascript to execute the event callback in the capture phase. you can look into it further at MDN.
button1.addEventListener("click", callBack, {capture: true} )
Advantage of Event Delegation
Well , this might come as a bad practice to a lot of developer out there (and i agree ) but there are certain use cases to execute the event in capturing phase. Suppose you want to add an event listener to an element that hasn't been added yet to the DOM. In these kind of scenarios you can add the event listener to the parent element and you can perform the appropriate action when this element gets clicked.
Handling event at the parent is event delegation, pretty cool right !!
Conclusion
By default all the event are executed in bubbling phase, i.e, when event bubble up from the point of origin to the farthest node in the DOM tree
Capturing is when the events are executed from the farthest away element to the point of origin of event i.e, from top of the DOM tree to the nearest DOM node
We can take advantage to event delegation to create a global event listener.
please feel free to ask questions, happy learning everyone !!