Sunday, March 8, 2015

jQuery, turn live() into on()

The jQuery live() method has been widely used, but it has been deprecated. It has been substituted by delegate (deprecated too) and after by the method "on". But lots of users find problems to reach with on the same effect of live().





The method .on() is totally equivalent to .live(), but most of developers just confuse the syntax.

In order to make .on() work like .live(), the correct syntax to use is:

$(document).on('click', '.myclass', function(e) { 
 var sender = $(this);
 // TODO: insert your code here! 
});

this command binds the click event to all existing elements containing the class "myclass" and, more important, to all elements that will be created in the future.

The wrong syntax, often used:

$('.myclass').on('click', function(e) { 
 var sender = $(this);
 // TODO: insert your code here! 
});

binds the click event only to all currently existing elements, if you add to the DOM a new element having the class "myclass", it will not fire the click event defined in the function.

No comments:

Post a Comment

(c) Copyright 2020 - MyTroubleshooting.com