0

I would like to know the difference between this:

$('#foo').click(function() {
  alert('User clicked on "foo."');
});

and this

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

(I read the documentation but I'm still not getting it).

alexchenco
  • 53,565
  • 76
  • 241
  • 413

3 Answers3

4

$().click(fn) and $().bind('click', fn) are identical at first sight, but the $.bind version is more powerful for 2 reasons:

  • $().bind() allows you to assign one handler to multiple events, e.g. $().bind('click keyup', fn).
  • $().bind() supports namespaced events - a powerful feature if you want to remove $().unbind) only certain event handlers that an element is bound to.
xkeshav
  • 53,360
  • 44
  • 177
  • 245
1

There is no difference but you can bind more than one event handler in one go using bind

$('#foo').click(function(){}) when triggered will call

$('#foo').bind('click', function() {})

So

$('#foo').click(function() {
  alert('User clicked on "foo."');
});

and this

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

means same.

Another use of bind is:

$('#foo').bind('click mouseover focus', function() {
  alert('User clicked on "foo."');
});

Hope this helps.

talha2k
  • 24,937
  • 4
  • 62
  • 81
0

The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs. The click() function does not bind multiple event handlers. The click() method triggers the click event, or attaches a function to run when a click event occurs.

$( "#button1" ).bind({
click: function() {
Do something on click
},
mouseenter: function() {
// Do something on mouseenter
}
});

and

$('#button1').click(function() {
alert('User clicked on button');
});
Mukesh Joshi
  • 2,784
  • 4
  • 24
  • 34