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 trialErik Larson
16,777 PointsWhat is the difference between using the "on" method versus the "click" method in this case?
I've used the "click" method before, but I am curious if there is a reason why the "on" method is used in this case.
2 Answers
Jesus Mendoza
23,289 PointsHey Erik,
With the .on method you can add selectors for dynamically added elements.
$('div').on('click', '.button', callback);
// Here you are targeting all buttons inside a div, even if they're dynamically added.
$('div .button').click(callback);
// Here you are targeting elements with the class .button but the click method wont work on dynamically elements.
So if you have dynamically added elements on your page and you want to add a click event listener on them you should use .on method, else you will be fine with just the .click method.
john larson
16,594 PointsThank you Jesus, that was a great answer.
Jesus Mendoza
23,289 PointsNo problem!
Brendon Butler
4,254 PointsI program in Java, not javascript, but if I had to take a guess..
I would say that the .on()
method is a more dynamic method. Whereas with the .click()
method, probably uses the .on()
method just for simplicity sake. I assume that you would be able to do something like this: $("button").on("hover", function(){});
but with the .click()
method, you're essentially stuck doing this: $("button").on("click", function(){});
.
If you're trying to decide what to use. I'd say go with the .click()
method. It simplifies your script and makes it probably a bit more understandable. From what I can tell, they would do the same thing.
Erik Larson
16,777 PointsErik Larson
16,777 PointsI guess I should clarify. I meant to ask this question in relation to the Intro to jQuery course. In a typical scenario, which is the preferred method to capture a click? $("button").on("click", function(){}); or $("button").click(function(){});