The third parameter - Event bubbling and Event capturing
I have been learning about events in JavaScript lately. I stumbled upon a very popular topic and learned something new that I wanted to share.


In the above code, one event listener targets the ul element as a whole. Whenever an image inside the ul element is clicked, the event fires, and it is logged in the console. Notice that the third parameter is set to false.



It's about event bubbling and event capturing.
As you can see, I have created a ul element with 5 images listed under it, each inside li elements. I've also added corresponding IDs to target each image and the ul element.
__________________________________________
In the above code, one event listener targets the ul element as a whole. Whenever an image inside the ul element is clicked, the event fires, and it is logged in the console. Notice that the third parameter is set to false.
Secondly, there's another event listener that gets triggered when the specific target sheep image inside the ul element is clicked, logging the corresponding message.
Now, note that the third parameter in both events is false, leading to two consequences:
Case 1: Event Bubbling (3rd parameter: false)
When an image inside the ul element is clicked (other than the sheep image), the log message corresponding to the first event is displayed. However, when the specific sheep image is clicked, the second event fires first, logging its message instead of the first message. This demonstrates that the inner event is bubbling up to the top, which is known as event bubbling.
Case 2: Event Capturing (3rd parameter: true)
Now, if the third parameter in both events is set to true, the results are reversed. When the sheep image is clicked, the first message is logged first, followed by the second message. This prioritizes the initial event, then moves to the subsequent events. This approach is top-to-bottom, whereas event bubbling is bottom-to-top.
But .. as the default parameter is false, when we need to prevent the event bubbling, the following method can be used:
e.stopPropagation()
e is the event object