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) {
    });
4
  • I've read that using .on is faster.
    – David G
    Commented Sep 5, 2012 at 15:51
  • As long as it's not a delegated click handler, pretty much nothing!
    – adeneo
    Commented Sep 5, 2012 at 15:55
  • 1
    @adeneo What is a delegated click handler ?
    – blue-sky
    Commented Sep 5, 2012 at 15:57
  • It's all very well explained in the documentation, but a delegated event is used for elements that does not yet exist in the DOM.
    – adeneo
    Commented Sep 5, 2012 at 15:58

3 Answers 3

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

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