0

Possible Duplicate:
Difference between .on('click') vs .click()

When handling a click of a div whats the difference between using .on and .click :

   $('#myDiv').on('click' , function(e) {
    });


    $('#myDiv').click(function(e) {
    });
Community
  • 1
  • 1
blue-sky
  • 51,962
  • 152
  • 427
  • 752

3 Answers3

2

Both are same...

.click is internally going to call .on method.

If you see the this part of jQuery source code.

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 ) :
            this.trigger( name );
    };

You can see that all the methods are in turn going to call .on method. So on will reduce your one level.

This is the implementation of .on in jQuery.

jQuery.fn.extend({

    on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
        var origFn, type;

        // Types can be a map of types/handlers
        if ( typeof types === "object" ) {.....
Vins
  • 8,849
  • 4
  • 33
  • 53
1

The later is a shortcut for the first.

The .on is more "low-level" and flexible. You can add a second parameter constraint the event to a selector, for example:

$('#myDiv').on('click' , "span.icon", function(e) {
    // this event will be fired when a click is made on a span.icon inside the #myDiv 
});
Marcelo De Zen
  • 9,439
  • 3
  • 37
  • 50
0

According to the docs, as of jQuery 1.7 .click():

this method is a shortcut for .bind("click", handler), as well as for .on("click", handler)

j08691
  • 204,283
  • 31
  • 260
  • 272