What is the different between:-
$("#btn").click(handler);
and
$("#btn").on('click', handler);
Both of the above will bind a handler to the element on click
event. When to use which one?
What is the different between:-
$("#btn").click(handler);
and
$("#btn").on('click', handler);
Both of the above will bind a handler to the element on click
event. When to use which one?
So as you can see from jquery source code .click
is just a helper function. Internally it maps the call to this.on( name, null, data, fn )
. So it is more of a convenience than anything else, internally all of this functions will call .on
.
Extra. You can also trigger this events with no params, which is what shorthand else does in this if statement. This will trigger DOM event on the element being called on, like emulating click with $button.click()
, which is again a shorthand for $button.trigger('click')
.
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
The .click() method is just a shorthand for .on( "click", handler ).For more details you can see this link https://api.jquery.com/click/