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 jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 3

why 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?

Paul McCann
Paul McCann
8,357 Points

The 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.

Samuel Webb
Samuel Webb
25,370 Points

Paul 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
John Yzaguirre
22,025 Points

the .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
Samuel Webb
25,370 Points

Andrew didn't use the second one because it wasn't necessary. Either would be fine.

Paul McCann
Paul McCann
8,357 Points

Thanks Sam.

The question had been corrected - the .controls selector in the second choice was missing the period initially.

Samuel Webb
Samuel Webb
25,370 Points

Ahh ok. I came to the party a little late :)