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

on("click", "li" function() {})

i dont get why we put a selector in the middle. documentation is unhelpful

2 Answers

Francisco Licea
Francisco Licea
9,260 Points

You 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
Steven Parker
229,608 Points

You'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.