Lesson 2 · Unit 03
Events
Capture and bubbling, target, delegation, preventDefault and stopPropagation
What you practise
- Capturing and bubbling, the target, delegation on a parent,
preventDefaultandstopPropagation
Try a question from this lesson
Pick one
The button sits inside the div, and each has a click listener. You click Buy. What is logged?
<div>
<button>Buy</button>
</div>
<script>
document.querySelector("div")
.addEventListener("click", () =>
console.log("card"));
document.querySelector("button")
.addEventListener("click", () =>
console.log("button"));
</script>Hint
A click on the button is also a click on whatever the button is inside.
Correct answer
button, then card
Why
The click starts at the button and then moves up to its parent, so both listeners run, innermost first, inside the one task that the click is. The order the listeners were attached in plays no part.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Bubbling
An event is not delivered to one element. After the element you clicked, it visits the parent, then the grandparent, all the way up the DOM tree to the document.
That journey is called bubbling. Every element on the way can listen for the event.
Concept
Down, then up
Before it bubbles up, an event first travels down from the document to the target. That is the capture phase.
Listeners run on the way up by default. Pass true as the third argument of addEventListener to run one on the way down.
click on <button> inside <div>
capture document, div
target button
bubble div, document10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.