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 trialErick Luna
21,076 Pointswhat is the difference between $('selector').click(); and $('selector').on(click,function(){}) in Jquery?
hello every one!! Can you say why to use one or the other sintax?
2 Answers
Steven Parker
231,269 PointsAssuming you meant to write that as "$('selector').click(function(){});
" and "$('selector').on('click',function(){})
", then there's no difference. The ".click()" function is simply a shorthand for ".on('click', )"
There are, however, other ways to use ".on" when given different arguments, such as for creating delegated handlers.
Also, if you really intended to write ".click()" with no arguments, that fires an event instead of creating the listener for one.
Dan Weru
47,649 PointsHi, the difference is in that one has an event listener. It is easier to explain with code.
$('selector').on(click, function(){
// do something
});
the .on() function is a javascript event listener. It listens for events such as click, hover, submit, double click, mouseover, mouseleave etc. Notice that these events are often triggered by a user. When that event (the even specified in the first argument) occurs, the code specified in the second argument (known as a callback and is almost always a function) gets executed.
$('selector').click();
In the second snippet there is no event listener. The code get executed as the click event happens, with no prior anticipation.
That's how I understand it.
Erick Luna
21,076 PointsThank you so much for the answer, it is pretty useful for me
Dan Weru
47,649 PointsYouβre most welcome. Happy coding!
Erick Luna
21,076 PointsErick Luna
21,076 PointsThank you so much for your answer Steven