Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: $().click(fn) vs. $().bind('click',fn);

People also ask

What is difference between click and Onclick in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

What is difference between on and bind in jQuery?

on() method is the preferred method for attaching event handlers to a document. For earlier versions, the . bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .

What is jQuery bind function?

jQuery bind() Method The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.

Is jQuery click deprecated?

click() shorthand is deprecated at jQuery 3 The . on() and . trigger() methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods.


For what it's worth, from the jQuery source:

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
    "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
    "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

    // Handle event binding
    jQuery.fn[name] = function(fn){
        return fn ? this.bind(name, fn) : this.trigger(name);
    };
});

So no, there's no difference -

$().click(fn)

calls

$().bind('click',fn)

+1 for Matthew's answer, but I thought I should mention that you can also bind more than one event handler in one go using bind

$('#myDiv').bind('mouseover focus', function() {
    $(this).addClass('focus')
});

which is the much cleaner equivalent to:

var myFunc = function() {
    $(this).addClass('focus');
};
$('#myDiv')
    .mouseover(myFunc)
    .focus(myFunc)
;

There is one difference in that you can bind custom events using the second form that you have. Otherwise, they seem to be synonymous. See: jQuery Event Docs


There is the [data] parameter of bind which will occur only at bind-time, once.

You can also specify custom events as the first parameter of bind.


I find the .click() is way more logical, but I guess it's how you think of things.

$('#my_button').click(function() { alert('BOOM!'); });

Seems to be about as dead simple as you get.