click() vs bind() vs live() vs delegate()

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”);
});
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.