click() vs bind()

Bind an event handler to the “click” JavaScript event, or trigger that event on an element.First, .click(function) is literally a shortcut for .bind(‘click’, function), they are equivalent.
Use them when binding a handler directly to an element.

Example 1:

$( “#div1” ).bind( “click”, function( e ) {

alert(“Click event using bind()”);

});

$( “#members li a” ).click( function( e ) {

alert(“Click event using click()”);

} );

Cons :

  • ย  ย  The method attaches the same event handler to every matched element in the selection.
  • ย ย ย  It doesn’t work for elements added dynamically that matches the same selector.
  • ย ย ย  There are performance concerns when dealing with a large selection.

Main difference between bind() vs delegate()
Example 2:

$(document).ready(function(){
$(“table”).delegate(“td”,”click”,function(){
alert(‘I am’ + $(this).text());
});
});

If we append new td dynamically in to the above table the click event will be apply for it(ie., it will apply for future
element also), but bind will not bind the event to the future element

bind() vs live()

The advantage of live and delegate function that they attaches event to those elements also which are added/appended after DOM is loaded.

ย Example 3:

$(‘a’).live(‘click’, function() { alert(“Thats New!”) });

jQuery binds the alert function to the $(document) element, along with ‘click’ and ‘a’ as parameters. Any time an event bubbles up to the
document node, it checks to see if the event was a click and if the target element of that event matches the ‘a’ CSS selector. If both are true,
the function executes.

Difference :

  • live function canโ€™t be used in chaining. live function needs to be used directly on a selector/element.

ย ย ย  for example : Wrong Code

$(โ€˜#fooโ€™).children(โ€˜tableโ€™).find(โ€˜tdโ€™).live(โ€˜clickโ€™, function(){
});

ย  for example : Correct code

$(โ€˜#fooโ€™).children(โ€˜tableโ€™).find(โ€˜tdโ€™).delegate(โ€˜clickโ€™, function(){
});

  • There is one more difference in terms of performance, if the context is not specified with the live function. Context means you are setting the search limit within a specific node.If you donโ€™t specify the context with live function then it attaches the handler to the document by default and when executed it traverse through the DOM which causes a performance issue.

$(document).ready(function(){
$(โ€œ#tble1 tdโ€).live(โ€œclickโ€,function(){
alert(“test”);
});

});

In the above code, no context is specified so event gets attached to the document by default. It causes a huge performance issue. But with jQuery 1.4, you can specify the context with live function also.

$(document).ready(function(){
$(โ€œtdโ€,$(โ€œ#tble1โ€)

[0]).live(โ€œclickโ€,function(){
alert(“test”);
});
});