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 trialalexialou
2,090 Pointswhy use $(".controls").on() instead of $(".controls ul").on()?
why use $(".controls").on() instead of $(".controls ul").on()? what's wrong with using the second one?
Samuel Webb
25,370 PointsPaul McCann it's not missing any period seeing that ul
isn't a class selector. It's an element selector so it doesn't need a period. The second example would be using a descendent selector (ul
is a child of .controls
) which is perfectly valid.
John Yzaguirre
22,025 Pointsthe .on() method requires a few things to work it's magic of updating the list element clicked in the video (to have the white circle appear around the new color).
$('.controls') is because .on() needs the PARENT element only (the div with the class 'controls'). This is the area this method is "listening" to, and waiting for any changes to jump in and run it's function.
.on('click' - this is because what used to be .click() is now .on() but 'click' is still the event needed which is why it is added within the parenthesis in quotations.
.on('click', 'li' - this is where the li part comes back in. It was at the beginning but now we are targeting the li from inside the .on() method. Now it knows to look for any changes within the div with the class 'controls', and if there is update on a 'click' on the 'li' level. At the end we can write in our function and what it is going to be doing.
.on('click', 'li', function() {
//do something here
}
2 Answers
Samuel Webb
25,370 PointsAndrew didn't use the second one because it wasn't necessary. Either would be fine.
Paul McCann
8,357 PointsThanks Sam.
The question had been corrected - the .controls selector in the second choice was missing the period initially.
Samuel Webb
25,370 PointsAhh ok. I came to the party a little late :)
Paul McCann
8,357 PointsPaul McCann
8,357 PointsThe second one wouldn't work because it is missing the period to denote a class selector :)
But I think your question is about which one might have lower overhead - in this simple example I would guess it wouldn't matter but I'd be curious to see if anyone else can comment on the effect of having the event bubble up 2 levels, instead of one, has on delegation.