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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Wilfredo Casas](https://uploads.teamtreehouse.com/production/profile-photos/5619632/micro_3fe9d5b9-d77c-4d45-a9be-42a20ab73216.jpg)
Wilfredo Casas
6,174 Pointswhy wouldn't I just use the on. method instead of this?
Why wouldn't I just use this
$('body').on('click', function() {
alert('clicked');
});
instead of this:
$('body').click(function() {
alert('clicked');
});
2 Answers
![Jesus Mendoza](https://uploads.teamtreehouse.com/production/profile-photos/2498332/micro_IMG_0205-copy2-240x240.jpg)
Jesus Mendoza
23,289 PointsHey Wilfredo,
With the .on() method you can specify a selector
$('body').on('click', '#button', (e) => {
});
That helps you to add click events to dinamically added elements. Let's say you have a function that adds a button depending on a selected option:
This wont work
$('#button').click((e) => {
console.log('I\'m a button');
});
But this works
$('#container').on('click', '#button', (e) => {
console.log('I\'m a button');
});
Have fun and merry christmas.
![ywang04](https://uploads.teamtreehouse.com/production/profile-photos/8077942/micro_xiaogua.jpg)
ywang04
6,762 PointsYou can refer to the jQuery API documentation: http://api.jquery.com/click/ Basically, .click() is is a shortcut for .on( "click", handler ) in the first two variations. Here, the handler means event handler or call back function.
Wilfredo Casas
6,174 PointsWilfredo Casas
6,174 PointsThanks Jesus and merry Christmas as well.
If the 'on' method has advantages over the 'click' method, is there any case where I would prefer to use the latter?