Learn about the DOM Event system through explorationWatch course
Legend
An event is a message that is dispatched to event target's.
There are many categories of events including user events such as 'click' and system events such as 'DOMContentLoaded'.
An event target is any object that implements the EventTarget interface (eg window, Element and XMLHttpRequest)
An event target can be the target of events and can have event listeners added and removed from them
When an event target participates in a tree 🌲 the event flows through the tree in three phases:
Capture listeners are called on the way down from the root to the target
Target listeners are attached to the target and they are called as the event passes through the target
Bubble listeners are called on the way up from the target towards the root.
The bubble phase will only occur if event.bubbles is true
An event's behaviour can be configured
bubbles: Conditionally allow the Bubble phase
cancelable: Conditionally allow an event to be canceled. Canceling an event prevents the events default behaviour
↓ See Listener effects below for more details about canceling events with preventDefault()
An event listener is a piece of code that you can register to be executed in response to a particular type of event.
el.addEventListener(
'click', listener
);
When binding an event listener there are three options that can be applied
1. Capture
Setting the capture flag controls whether an event listener is called in the Capture phase or Bubble phase
el.addEventListener(type, fn,
// capture listener
{ capture: true }
// bubble listener
{ capture: false }
)
2. Passive
Setting the passive flag to true marks the event listener as passive
el.addEventListener(type, fn,
{ passive: true }
)
↓ See Passive events below
3. Once1
Setting the once flag to true causes the event listener to be automatically removed after a single call
el.addEventListener(type, fn,
{ once: true }
)
In addition to its own processing, an event listener can perform up to two side effects:
1. Preventing behaviour
preventDefault
Cancels an event and prevents the default browser behaviour associated with an event
event.preventDefault()
Can only be used on events that are cancelable
↑ See Event options above
Cannot be used by passiveevent listeners
↓ See Passive events below
2. Stop an event
stopPropagation
Will stop the event once it has finished processing all of the event listeners on the current event target in the current event phase
event.stopPropagation()
stopImmediatePropagation
Will stop the event straight away. No other event listeners will be called
event.stopImmediatePropagation()
When adding an event listener you can specify whether it is passive. If all event listeners on an event path are passive, the the browser can defer dispatching the event.
passive event listeners are not allowed to cancel events
(withevent.preventDefault())
as the browser action associated with the event can be finished before the event listener is called.