Benefits / differences of jQuery in .trigger () vs .click ()

In terms of performance, what are the benefits (or just differences) between:

$('.myEl').click(); 

and

 $('.myEl').trigger('click'); 

Is there anyway?

+49
jquery
Mar 12 2018-12-12T00:
source share
4 answers

This is the code for the click method :

 jQuery.fn.click = function (data, fn) { if (fn == null) { fn = data; data = null; } return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click"); } 

as you can see; if no arguments are passed to the function, it will raise a click event.




Using .trigger("click") will call one smaller function.

And as @Sandeep pointed out in the answer .trigger("click") faster:




Starting with version 1.9.0, checking for data and fn been transferred to the .on function :

 $.fn.click = function (data, fn) { return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click"); } 
+43
Mar 12 '12 at 11:56
source share

for the kind of performance .check here. http://jsperf.com/trigger-vs-not-trigger Both are pretty much the same ... click () is a shortcut for the trigger ('click').

+2
Mar 12 2018-12-12T00:
source share

I think that

 $('.myEl').trigger('click'); 

better because it saves you a function call since $('.myEl').click(); just calls it funciton. Look at the code from jQuery source

 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 ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : //here they call trigger('click'); if you provide no arguments this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); 
+1
Mar 12 2018-12-12T00:
source share

Check out http://api.jquery.com/click/ :

In the third option, when .click () is called without arguments, it is a shortcut to .trigger ("click").

They seem to be the same.

0
Mar 12 2018-12-12T00:
source share



All Articles