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

CSS jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 3

Can anybody explain why .on() works for the new list items while .click() only works on the original list items?

As seen in the video, we had some issues getting the dynamically created list items to recognize a click event. Why does .click() not work for all of our new list items?

3 Answers

Ryan Field
PLUS
Ryan Field
Courses Plus Student 21,242 Points

So when you use a method like .click() in your jQuery code, the script binds that listener to the elements that are there when the page first loads. However, jQuery/JavaScript doesn't know about new elements created on the page, so it can't use the same listener for those. The .on() method tells jQuery to continue to listen for new elements created that match the selector, and will bind whatever action/function you want to both elements there when the page is loaded and any new ones created after initial loading.

Craig Curtis
Craig Curtis
19,985 Points

Yep, if you create new DOM elements, use an .on() event handler. Other guides also recommend using the .on() handlers over the typical click/mouse/window event functions.

You have to bind the new list item to the list. I don't remember how off the top of my head. I don't think it is the bind function, though. It was covered in one of the early JavaScript courses in the front end development track.