Event Capturing & Event Bubbling: Basic JavaScript Concepts
Two of JavaScript’s most intriguing ideas are event bubbling and event capturing. Before we get into these fascinating ideas, let’s first discuss:
What is an Event listener?
A function that waits for an event to happen is an event listener. Any event, such as a mouse click, the submission of a form, the pressing of keyboard keys, etc., can count as that event.

The propagation of events is referred to in JavaScript as “Event Flow.” The sequence or order in which events are delivered to a particular web page is known as the event flow.
The following factors affect how an event flows.
1)- Event Bubbling
2)- Event Capturing
Event Bubbling —
When two items are nested inside of one another, and both of them have registered a listener for the same event. The sequence in which the event handlers are called is known as “event bubbling” (a click, for example). When an event is bubbling, the innermost element initially records and manages it before propagating to the outer components.

The event handler of element2 fires first, and the event handler of element1 fires last.

Event Capturing-
When two items are nested inside of one another and both have registered a listener for the same event, the order in which the event handlers are invoked is known as event capturing (a click, for example). When an event is captured, the outermost element first records it before propagating it to the inner components.

The event handler of element1 fires first, and the event handler of element2 fires last.

How can event capturing and event bubbling be stopped?
When we add an event listener to an element, an event object that automatically defines itself is created. StopPropagation(), a function on this object ‘e’, aids in stopping this unpleasant behaviour.

Notes-
- Event bubbling will occur by default if we do not specify a third option in addEventListener().
- When an element and all of its ancestors have the same event listener (in this case, the “click” event) attached with them, then event bubbling and event capturing take place.