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

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

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

and

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

Are there any at all?


Solution 1:

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:

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:

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