Andrew's Digital Garden

Events in Javascript

Events go through three phases:

Capture phase: events traverse down through elements checking for event handlers on each handler, calling it if it exists (starts at html and then its descendents) Target phase: browser checks to see if the target property has an event handler for the event registered Bubbling phase: the opposite of the capture phase, with events traversing up (starts at the element and then its ascendents)

The default for an event listener is to register for the bubbling phase. Default: bubble

This traversal is known as propagation, with events propagating both up and down. stopPropagation stops an event from propagating when called, effectively ending its traversal regardless of direction. i.e. stopping during the capture phase will prevent the bubble phase entirely.

stopImmediatePropagation stops the propagation happening for the same element, which is only helpful when there is more than one event handlers tied to it. Event handler #1 (defined first) can stop #2 from being called.

preventDefault is different from the event traversal entirely - it stops the default action of the element, e.g. prevent a a from navigating.

https://web.dev/eventing-deepdive/

[[js]]

Events in Javascript