Event Propagation and Trees

There are many quirks with Javascript DOM manipulation. One of the quirkiest of quirks a budding programmer will come across in his/her quest for knowledge is the concept of event bubbling. This refers to the order of which event elements are called when one element is nested inside another element. For example, when I used React for a project for the first time I tried to make a hide-able card that had another hide-able details element inside of it. But, when I put click listeners on both elements, clicking on the nested element would trigger both listeners and hide the whole thing every time.
The situation that I witnessed on my first React project was something called event propagation and has to deal with the way in which events are handled in the DOM tree. But before we jump straight into event propagation, it’s best to receive an explanation of what the DOM data structure is — a tree — and what it’s used for.
What is and why a tree?
A tree in this sense is a hierarchical datatype that has a root node connected to subtrees of nodes called children. This datatype is best used with applications that require tasks to be delegated down from one root element to it’s subordinate element(s) in a hierarchical manner like a corporate structure.

There are six terms to know when dealing with trees.
The Root is the highest parent node. It’s the child of no one and the parent of all the other nodes.
The Link or Edge is the reference that is used to link the parent to the child node.
A Child is the node succeeding a parent node in which it’s connected to.
The Parent is the upper node that is linked to a child node.
Siblings are any group of nodes that are children of the same parent node.
And a Leaf is any node that doesn’t have children.
So why do events propagate anyway?
The term event propagation is an over-arching phrase used to describe both bubbling (when the order of events propagate upward towards the root) and capturing (then the order of events propagate downward towards the leaves). Both of which are critical to the way the DOM functions.


Event propagation can be broken up into three phases.
- The capturing phase: when the event moves downward towards the target.
- The target phase: when the event hits the target.
- The bubbling phase: when the event moves back upward towards the window.

It’s good to note that while all events will flow downward from the window to get to the target, some events (focus, blur, load, etc.) won’t actually hit the bubbling phase at all.
But remember, the DOM tree is hierarchical in nature. So if the event needs to retrieve a value from the target, it will always need to bubble back to the root of the DOM (the window).
And that’s it! The effects of event propagation are fairly odd, but the basic concepts are actually fairly simple!
