Day 25 of #javascript30 explains what happens when (DOM) events are triggered.
I made a pen based on the lesson to try to illustrate and understand better. It's at the bottom of this post.
Bubbling
Is when an event "bubbles" up the DOM. In the example with 3 nested divs with an event listener on all of them, a click on the inner one will trigger the click listener on all of them. Note that this
is the item the listener is on, but event.target
is always the item that was clicked.
Propagation
In JS this means that the event will keep bubbling up (or capturing). If you call e.stopPropagation() the propagation stops.
Event listener parameters
The addEventListener() function takes an optional options object. Of these, capture
and once
are interesting.
once
Will allow the event to fire once and then remove the event listener.
capture
I think the easiest way for me to understand this is that when this is true, the events bubble backwards. Try playing around with the pen example to try and make sense of it :)
See the Pen Event options and propagation by Camilla Krag Jensen (@naxoc) on CodePen.