Is there any advantage to using jQuery $ (). On ('mouseenter', function () {}) over $ (). Mouseenter (function () {})?

I often see code like:

$("#thing").on("mouseenter",function(){ Do stuff }); 

Personally, I almost always write:

 $("#thing").mouseenter(function(){ Do stuff }); 

Similarly, I often write

 $("#thing").click(function(){}) 

but I saw how people fix it (yes, I know that on preferable to bind in version 1.7+, so it is essentially the same question):

 $("#thing").bind("click",function(){}) 

I am doing something "wrong", is there a deep difference between the two functions that I do not see? It always seems to me that I am doing this, so this has never been a problem for me, but I would be interested to know if there is a theoretical consideration that I am losing sight of.

+3
source share
4 answers

Actually, this is slightly faster, since the mouseenter function calls on (or trigger if called without an argument), as seen in the source code:

 jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); 

As you can see, the same can be said for many events.

Personally, I prefer to use the mouseenter function (or click , etc.) when I do not need special on functions: one of the big advantages, in my opinion, in using jQuery is that it makes the code less verbose and more readable. And I don’t think you should be corrected, ask the guys who are correcting you why he does it.

+7
source

Usually events like .click or $.post are shortcuts. They act in the same way as the .on and $.ajax , but the latter usually have more flexibility. EG .on can communicate with several events, while .click subscribes only to clicks. The same applies to the $.ajax function, there are more options where certain default values ​​are set in the shortcuts.

+2
source

There is no practical difference between the two, abbreviated functions ( .click() , .mouseover() , etc.) call .on() to actually bind an event handler. The only "advantage" in using .on() is that you do not have the additional overhead of calling the second function; I suspect it is likely to be quite marginal, although it will be premature optimization.

+1
source

This is not necessarily wrong, but has its advantages over the conventional method.

Under the "binding" of the event to your parent container $(parent).on(event, target, function() { //foobar }); you can add new target elements to your container without requiring jquery repetition to bind the event.

+1
source

Source: https://habr.com/ru/post/1202855/


All Articles