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 trialJay G
2,904 PointsUsing .on() instead...
I've been told that when using event listeners, you should use $(selector).on(event)...
$('.spoiler button).on('click', function(){
$('.spoiler span').show();
$(this).hide();
})
for event delegation, particularly when using aJax? Thoughts?
2 Answers
Stoyan Peshev
6,683 PointsYou can either use .click or .on, but you can do tricks with .on syntax. (Also: .click adds an event listener for every element, while .on works with on listener for all elements found.) For example, you can dynamically delegate events based on what you need at the moment, like in this case:
function subscribeTo(element, event, callback) {
$(element).on(event, callback);
}
You can use different scenarios based on what platform your code is running on (PC/Mac, mobile etc.).
Samy Basset
11,862 PointsYou can use events with dynamicly created elements with .on(), with .click() you can't.,