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
  • 50,467
  • 73
  • 227
  • 400

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.
diEcho
  • 52,196
  • 40
  • 166
  • 239
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.

AlphaMale
  • 24,318
  • 4
  • 59
  • 79
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');
});
M.J
  • 2,394
  • 4
  • 21
  • 33