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 trialsibal gesekki
3,484 Pointson("click", "li" function() {})
i dont get why we put a selector in the middle. documentation is unhelpful
2 Answers
Francisco Licea
9,260 PointsYou can think of it this way if it helps: Hey 'p' element, when the user clicks on you check if the click happened on an 'a' element inside of you, if so then hand over the click to it and execute the function.
$("p").on("click", "a", function(){
//hide the <a> that was clicked
$(this).hide();
});
It doesn't matter if the 'a' exists when the DOM is first loaded or if it is created dynamically, because we are actually asking the 'p' for its existence until we click on it.
Steven Parker
231,275 PointsYou're missing a comma, it should be:
on("click", "li", function(){})
That's a delegated event handler. instead of being attached to the item that will be clicked, it is attached to an ancestor element. The advantage is that the handler will operate on elements that are created after it was attached. The middle argument selects which elements will actually be clicked to fire the event.
In the video, the code creates new buttons when a color is selected. The delegated event handler is used so when a new button is created, clicking on it will cause the action to occur, even without explicitly attaching a click handler directly to the button.