Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialUmar Ghouse
14,607 PointsWouldn't event.target also refer to other elements?
In this video, we add an event listener to the ul element - but this listener isn't for the ul, it's for the checkbox that is a child of the ul (code given below)
HTML:
<ul id="invitedList">
<li>
<label>
<input type="checkbox">
</label>
</li>
</ul>
JavaScript:
ul.addEventListener('change', (e) => {
const checkbox = event.target;
const checked = checkbox.checked;
const listItem = checkbox.parentNode.parentNode;
if (checked) {
listItem.className = "responded";
} else {
listItem.className = "";
}
});
We have an event.target expression assigned to the variable "checkbox". Let's assume, for the sake of this question, that the event listener was looking for a "click" event, instead of a "change" event. In that case, would it have triggered this block of code if we clicked the label? or the li? (i.e. anything besides the checkbox).
If so, why not target the checkboxes directly, instead of relying on bubbling through the ul? Wouldn't that reduce the margin for error?
Thanks in advance!
1 Answer
Steven Parker
231,269 PointsYou're quite right about how a delegated handler works.
If this handler had been for a click event, then additional could would be needed inside to qualify the target. But no additional filtering is needed for the change event, because the checkboxes are the only elements inside the ul
(including itself) that can generate that specific event.
There are two advantages of using the delegated handler: first, it only requires one to handle every checkbox. And second, it will be effective on those added later, when an individual handler would have to be added to any new checkbox element.
Umar Ghouse
14,607 PointsUmar Ghouse
14,607 PointsOh OK. I get it now. Thank you for the brilliant explanation!
Zhenghao He
Courses Plus Student 2,389 PointsZhenghao He
Courses Plus Student 2,389 Pointswouldn't it be better to write
const checkbox = e.target;
or does event has some semantic meaning?Steven Parker
231,269 PointsSteven Parker
231,269 PointsThe variable "event" is established by the browser, but I agree it's better to use the argument passed in.