When an event is fired on an element, it propagates down from the top level of the document until it reaches that element,
in what is called the capturing phase.
Some events will then also bubble up from the element until they reach the top level of the document again.
Listeners can be registered so that they handle events either during the capture phase or the bubbling phase.
This allows a listener registered on an element to handle events fired on its children,
so for example a listener registered on the document can handle any event.
Sometimes—such as when designing re-usable components—it is desirable to override such global listeners,
or alternatively, to have global listeners override listeners on elements lower in the DOM.
Listeners can do this by calling
event.stopPropagation(), which stops the event from propagating past the element the listener is registered on.
If the listener is registered using
useCapture, this stops the event during the capturing phase so that it will never reach the child elements
and never bubble. For example, a listener registered on the document using
useCapture can prevent events from being handled by any other element.
If the listener is registered on the bubbling phase (the default), the event will go through its capture phase normally but will stop bubbling up,
and so can prevent the event from being handled by a listener on the document that is registered on the bubbling phase.
Mouse events in particular are surprisingly complex and easy to handle incorrectly. There are many different events that can be fired as a result of mouse interactions, including:
divs that share a border), this fires only on the lowest element in the DOM that was entered, and bubbles up.
Click around inside the three containers to see the types and orders of events fired. The events will be added to a queue to the right as they are received by listeners on each element, and played back in order.