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 trial

JavaScript

Sean Barry
Sean Barry
4,264 Points

How does the ul listener know to only listen for checkbox clicks and not other clicks?

ul.addEventListener('change', (c) => { const checkbox = event.target; const checked = checkbox.checked;

});

The listener is being applied to the entire ul. Could someone please go more in depth as to why it only responds to checkbox checks? It'd really help me understand what's going on better. Thanks

3 Answers

Steven Parker
Steven Parker
231,271 Points

The event type is the key.

There was a bit more code added to that handler, but nothing that would filter the target. But it's not a click event that is being listened for here, it is a change event. And change events are only fired for <input>, <select>, and <textarea> elements. Since the checkboxes are <input> elements, and the only elements of those 3 types within this unordered list, then this listener will only receive events for the checkboxes.

Sean Barry
Sean Barry
4,264 Points

So there was no filtering because there was no need. That definitely filled in the gaps. Thank you. Sorry for all the confusion, I tend to overthink things to where it becomes counterproductive.

Steven Parker
Steven Parker
231,271 Points

Your question is a good one, and may benefit other students who are puzzled by the same thing.

use the is(":checked"); or you can use prop("checked");

Sean Barry
Sean Barry
4,264 Points

But what if the event.target isn't a checkbox? Won't that cause bugs?

Steven Parker
Steven Parker
231,271 Points

This code looks incomplete.

It sets some variables, but doesn't perform any action. It could be that you're at a point in a lesson where this handler is being constructed but isn't finished yet. And at that point, there may be some more code that will clear up this question.

But if you'd like to post a link to the course page (always a good idea with any question), I can give you a more definitive answer.

Sean Barry
Sean Barry
4,264 Points

It's in the context of the RSVP Checkbox Javascript video in the course "DOM Scripting By Example". It's straight from the lecture. I know how to make the code work, I just dont get the "why" behind how it only applies to checkboxes

Steven Parker
Steven Parker
231,271 Points

Ok, I found it. A direct link to the video would be handier, though.