DOM Events
Various user actions can trigger an event. The event target is the innermost element at the relevant location for the event, such as the location of the cursor when a mouse button is clicked. For example, if the event occurs where text content is displayed, the target element is the parent element of the text node. The event is propagated through various elements in the DOM hierarchy initially from top to bottom, down to the target element of the event, and then back to the top:
- The event propagates down from the Window to the Document then down through the ancestors of the target element to the parent of the target element. This is called the capture phase. As the event propagates through each node, any event listeners added with the useCapture addEventListener parameter set to
true
will be dispatched in the order that they were registered. - Propagation of the event reaches the target node. This is called the at target phase. The target's event handler will be dispatched, if any, followed by any registered event listeners in the order they were registered.
- The event propagates back up from the parent of the target element to the Document and then the Window. This is called the bubbling phase. Some events may not bubble up. As the event propagates through each node, the node's event handler will be dispatched, if any, followed by any event listeners registered with the useCapture addEventListener parameter set to
false
.
Window |
↓ ↑ |
Document |
↓ ↑ |
<html> HTMLHtmlElement |
↓ ↑ |
<body> HTMLBodyElement |
. ↑ |
. . |
. . |
↓ . |
etc. HTMLElement |
. ↑ |
. . |
. . |
↓ . |
target's parent HTMLElement |
↓ ↑ |
target HTMLElement |
Events are dispatched to event handlers and event listeners to the registered event listeners and HTML elements based on the DOM element hierarchy at the time the event is initially dispatched. The event flow does not change even if listeners are registered or removed or if the DOM element hierarchy is changed by some of the event handling code.