Live() vs. Delegate()
both are use to attached event to current element and future elements which we append after DOM loaded e.g. we load some table rows using ajax.
but still they have difference…
let start with live()
Its attached directly to elements like class or id but not be used with chaining.
Right use of live
$(‘a’).live(‘click’, function(){
blah blah...
});
Wrong use not possible (chaining)
$(‘#foo’).children(‘table’).find(‘td’).live(‘click’, function(){
blah blah...
});
This is possible with delegate
$(‘#foo’).children(‘table’).delegate(‘tr’, ‘click’, function(){
blah blah...
});
Another difference is performance
Context is defining the search limit to bubble to top level of element.
Live() default context is document…. so it bubble till document which cause the performance issue.
In Query 1.4 they provided option to define context for live other then document
$(‘a’, $(‘#mytable’)[0]).live(‘click’, function(){
blah blah...
});
In delegate you can set context which cause less traverse
$(‘#mytable’).delegate(‘a’,‘click’, function(){
blah blah...
});
So better to use delegate all the time instead of live() and bind().
