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 trial2 Answers
Stephen Gheysens
11,935 PointsHi Akhter,
The $.on() method has two main differences from the usual $.click() event handler binding method. First off, you get the opportunity to define what type of event should be listened for, it doesn't have to be limited to a "click" - there are lots of events that a user could cause to happen, like a mouseup or keydown event. I added a link below to the MDN docs for standard events, it's pretty crazy how many different types of user interaction you can listen for! The other major difference you'll notice is that the $.on() method binds event handlers to both current and future elements that match the selector. In the lesson, extra color palettes are added after the original click event handler was connected to the <li> elements, but by using $.on(), the browser also listens for the events on <li> elements that are added later by user interaction.
$.on() documentation - http://api.jquery.com/on/ Standard Events MDN docs - https://developer.mozilla.org/en-US/docs/Web/Events
Chyno Deluxe
16,936 PointsHello Akhter, The on() method is used when you want to add functionalities to specific events like a click event or keydown event or other event types. You can get more information about the on() method on jQuery website.
I hope this helps.
Akhter Rasool
8,597 PointsCould you explain with an example ?
Chyno Deluxe
16,936 PointsHere is a quick example: jsFiddle:
Akhter Rasool
8,597 Pointsthanks!!
Akhter Rasool
8,597 PointsAkhter Rasool
8,597 Pointsthanks!!!!!
Jeremy Castanza
12,081 PointsJeremy Castanza
12,081 PointsGenerally speaking... is it better to just use the on() method over the click() event handler - given the customization that you can do with the parameters? Trying to think of an instance when it would be better to use click() vs. on().