jQuery advantages/differences in .trigger() vs .click()

Jquery

Jquery Problem Overview


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

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

and

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

Are there any at all?

Jquery Solutions


Solution 1 - Jquery

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");
}

Solution 2 - Jquery

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;
	}
});

Solution 3 - Jquery

for performance kind .check here.. http://jsperf.com/trigger-vs-not-trigger Both are almost same...click() is shorthand of trigger('click').

Solution 4 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbenhowdle89View Question on Stackoverflow
Solution 1 - JqueryAndreas LouvView Answer on Stackoverflow
Solution 2 - JqueryNicola PeluchettiView Answer on Stackoverflow
Solution 3 - JquerysandeepView Answer on Stackoverflow
Solution 4 - JqueryPawel ZubryckiView Answer on Stackoverflow