In terms of performance, what are the gains (or just differences) between:
$('.myEl').click();
and
$('.myEl').trigger('click');
Are there any at all?
on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not. When .
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.
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"); }
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; } });
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