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 trialGuy Noda-Bailey
18,837 Points.on() jQuery the *childSelector*.
Here is the code that works as shown in the example;
$(".controls").on("click", "li", function(){.....etc
I'm not sure why Chalkley's first attempt at this didn't work;
$(".controls li").on("click", function(){.....etc
as the documentation suggests that the childSelector is optional, and that if it is left out or null then the event will be triggered when it reaches the selector. So why didn't his first attempt just work on the .controls li ?
3 Answers
Jason Anello
Courses Plus Student 94,610 PointsHi Guy,
The 1st attempt does work for the 3 existing list items that are already in the html but doesn't work for the new ones added in later.
What happens is that when that code is run the selector will match the existing 3 li's and attach click handlers to each of them. However, new list items added will not have a click handler attached to it because they did not exist at the time the .on
code was run. So they don't respond to clicks but the original 3 do.
With the second attempt you're using event delegation. You may want to read that section in the documentation.
$(".controls").on("click", "li", function(){.....etc
With this code you are attaching a single click handler to .controls
and then by passing in that second parameter "li" you're saying that li's are the only descendants that can trigger this event. So when you click on any li
, pre-existing or newly added, it will trigger the event and that event will bubble up to .controls
where the click handler is attached and that handler code will be executed.
Neal Gist
8,438 PointsAre you loading in content dynamically at all? I'm just speculating here... if you have any live examples or a JS fiddle, that would help!
If an <li> element is added through ajax, the second function in the example above would not delegate the event to the new <li> element. Targeting just ".controls" will work since it relies on the event bubbling up from the click instead.
If you're not loading content dynamically, I don't know what to tell ya man... good luck!
Guy Noda-Bailey
18,837 PointsThanks Jason and Neal, you guys helped me understand this concept. I totally had the wrong idea about what .on() did until you pointed me in the right direction.