Thursday, January 2, 2014

Difference between .on and .live in JQuery

.live
Usually we are using this method for, adding a action for a dynamically created element.

For example: 
Say our user has to enter his friends email on our site. But our page initially has, only one text box with a "add new email" link. So now, when user click on "add new email" link we will call a JS code to generate a new text box with a delete a option.

That is we are write this code under,
$('#add_new_id').click(function(){

      ----- code to generate new text box with a delete link ------

});

But now we have to call delete action, when user click on delete option. If we are simply write as previous one like $('#delete_link').click it will not work. Because we dynamically generated this link. So we write a code as follow,

$('#delete_id').live('click',function(){

      ----- code to delete text box ------

});

Issues on .live
As of JQuery 1.7+ .live is not recommended, you can check this here. Because,

1. jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents.

2. Chaining methods is not supported. For example, $( "a" ).find( ".offsite, .external" ).live( ... ); is not valid and does not work as expected.

3. Since all .live() events are attached at the document element, events take the longest and slowest possible path before they are handled.

And more issues, you can look here.

Use .on instead of .live
We can use "on" through all elements whether the element is loaded previously or dynamically.

Syntax for 'on':
$(document).on(event, selector, action);

Example for using 'on', instead of '.live':
$('#delete_id').live('click', function() { } );   // Don't use this.
$(document).on('click', '#delete_id', function(){ } );   // Use this.

Note:
On the above example we select or search '#delete_id' element directly from 'document'. We can still search under a nearest element as, $('#nearest_known_div_id').on('click','#delete_id', function(){ } );.

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...