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 Introduction to jQuery Events Intro to Events

why 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
Jesus Mendoza
23,288 Points

Hey 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.

Thanks 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?

ywang04
ywang04
6,762 Points

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