Submodule 14.3: DOM events
Submodule 14.3: DOM events
Capturing and Bubbling
As we learned, there are two phases where the event can be executed, the Capturing and Bubbling phase.
To explain the different phases we will look at an example where we have elements inside other elements and all of them have event handlers.
Exercise
- Open your editor, create a new file and save it as
exersice14.3.1.html
in the folder "yourNameWEB2JS". - Copy the code below and paste it in the new file.
- Open the file in your browser and "Click me" to see the results.
Note the third parameter, useCapture which is false and thus the event takes place at the bubbling phase.
What happens when you click at the "Click me" ?
You first get the alert for that 3rd div, then the one of the second - red div and finally the one for the outer - green div.
Now, go ahead and change the useCapture to true on all eventListeners. Click again on the "Click me ". What do you see?
The events are occurring on the opposite order, starting from the green div, then going to the red and finally to the paragraph.
The above shows the difference between capturing and bubbling.
In the bubbling phase, the event occurs on the deepest element and then triggers on parents in nesting order, whereas on the capturing phase, it first occurs on the outermost element and then goes to the inner elements.