I frequently 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 have seen people correct it to (yes, I know on is preferred over bind in v. 1.7+, so it's essentially the same preference issue):
$("#thing").bind("click",function(){})
Am I doing something "wrong", is there a deep difference between the two functions that I'm not seeing? It always seems to do what I want it to do, so it's never been a practical concern, but I'd be interested to know if there's a theoretical consideration I'm overlooking.
Not really, it's just a little faster as the mouseenter function calls on (or trigger if called without argument) as can be 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 (or click, etc.) function when I don't need the special features of on : 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 corrects you why he does that.
Normally, the specific events like .click or $.post are shortcuts. They act the same as using the .on and $.ajax functions but the latter normally have greater flexibility. EG .on can bind to multiple event while .click only subscribes to clicks. Same applies to the $.ajax function, there are more options where as the shortcuts have certain defaults set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With