DEV Community

jun
jun

Posted on

Explain Event Bubbling Like I'm Five

What is event bubbling vs capturing? Please explain to me like I'm a kid who doesn't know any strong technical jargons! Thanks!

Top comments (5)

Collapse
 
thuvvik profile image
thuvvik

Bubbling:
You are in your classroom, and you say to your teacher "I have a headache".
The teacher will tell the director, the director will call the school nurse
The school nurse will handle the situation..

From you to upper in a "hierarchy"... the event information "kid X has a headache" is processed (a bubble in the water would go "up")

Capturing:
Your parents were quite disorganized today, they came back to the school door before lunch, and left your lunchbag (with your name on it) to the director.
The director gives the lunchbag to the teacher.
The teacher gives you your lunchbag.

From upper in the hierarchy to you, the event information "a lunchbag for you" has been processed (given the lunchbag has your name pn it, only you can "capture it"/open it)

Collapse
 
evanplaice profile image
Evan Plaice • Edited

Firing an event is like taking a notes in class. You can write notes to yourself (capture) or write notes for others (dispatch).

When you send a note to someone else (dispatch), it'll get passed to the next person (parent) in the chain.

Each person it doesn't belong to passes to will pass it on (bubble).

When the person who it's intended for (has an event listener) receives it they will open it.

If it was intended for them, they can keep.it (event.preventDefault()).

If it was meant for multiple people then can pass it on after they read it (no preventDefault()).

Imagine all notes that don't get captured end up at with the teacher (document). If you want something passed from anybody, tell the teacher to listen for it.


This metaphor works for events you create and pass. But the reality is anything can create an event and the browser fires off events for every interaction.

Any element in the tree from where the event is fired up to the root can listen for the event and respond to it.

The top of the tree is where the browser sees that something happened. That's why events bubble by default.

Collapse
 
westbrook profile image
Westbrook Johnson

Not “simple” because it’s not really, but thorough: dev.to/open-wc/composed-true-consi... Hopefully it’s useful and you learn something about related concepts in the land of events!

Collapse
 
truonghan0812 profile image
truonghan0812

Not sure is this simple enough for you, hope it help:
dev.to/clickys/bubble-vs-capture--...

Collapse
 
junlow profile image
jun

Thanks for so many creative answers!!