Reputation: 37504
In terms of performance, what are the gains (or just differences) between:
$('.myEl').click();
and
$('.myEl').trigger('click');
Are there any at all?
Upvotes: 80
Views: 29836
Reputation: 47127
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 trigger the click event.
Using .trigger("click")
will call one less function.
And as @Sandeep pointed out in his answer .trigger("click")
is faster:
As of 1.9.0 the check for data
and fn
has been moved to the .on
function:
$.fn.click = function (data, fn) {
return arguments.length > 0 ? this.on("click", null, data, fn) : this.trigger("click");
}
Upvotes: 69
Reputation: 76910
i think that
$('.myEl').trigger('click');
is better because it saves you a function call as $('.myEl').click();
just calls that 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;
}
});
Upvotes: 5
Reputation: 2234
for performance kind .check here.. http://jsperf.com/trigger-vs-not-trigger Both are almost same...click() is shorthand of trigger('click').
Upvotes: 3
Reputation: 2713
Check http://api.jquery.com/click/ :
In the third variation, when .click() is called without arguments, it is a shortcut for .trigger("click").
It seems they are the same.
Upvotes: 2