Site icon Dotnet Helpers

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 :

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 :

    for example : Wrong Code

$(‘#foo’).children(‘table’).find(‘td’).live(‘click’, function(){
});

  for example : Correct code

$(‘#foo’).children(‘table’).find(‘td’).delegate(‘click’, function(){
});

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

Exit mobile version