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 Hello, jQuery! Accessing and Modifying Attributes

Erick Luna
Erick Luna
20,282 Points

what 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
Steven Parker
229,732 Points

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

Erick Luna
Erick Luna
20,282 Points

Thank you so much for your answer Steven

Dan Weru
Dan Weru
47,649 Points

Hi, 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
Erick Luna
20,282 Points

Thank you so much for the answer, it is pretty useful for me

Dan Weru
Dan Weru
47,649 Points

You’re most welcome. Happy coding!