Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an advantage to using jQuery's $().on('mouseenter',function(){}) over $().mouseenter(function(){})?

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.

like image 920
Jason Nichols Avatar asked Dec 03 '25 16:12

Jason Nichols


2 Answers

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.

like image 50
Denys Séguret Avatar answered Dec 06 '25 06:12

Denys Séguret


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.

like image 32
Justin Avatar answered Dec 06 '25 05:12

Justin