0

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?

3
  • second one used when elements added/created through jquery itself. btw it will work for both Commented Feb 16, 2017 at 10:23
  • @Anant so you mean when the element that is added is dynamically added ?
    – Shubham
    Commented Feb 16, 2017 at 10:30
  • @Shubham check the given link you will get proper explanation Commented Feb 16, 2017 at 10:31

2 Answers 2

1

The .click() method is just a shorthand for .on( "click", handler ).For more details you can see this link https://api.jquery.com/click/

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.