Reputation: 152216
As described on http://api.jquery.com/live/
:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Right. So instead of
$('.dynamicallyCreatedElement').live('click', function(){
console.log('click');
});
I should use:
$('.dynamicallyCreatedElement').on('click', function(){
console.log('click');
});
However it does not bind event to elements created after on()
calling. So is it really better live()
method ?
Am I missing something ?
Upvotes: 30
Views: 9586
Reputation: 16174
To use on
in the same manner as live
used to work you need to use it like:
$(document).on("click", ".dynamicallyCreatedElement", function() {
console.log('click');
});
So you bind the on
handler to the document
itself (or, actually, the container element where the new wlements will be "appearing" -- Thanks to @devnull69 for the clarification), then pass it an event type and the selector.
You'll find a couple of examples halfway through the live
documentation page.
Upvotes: 63
Reputation: 3801
Use as delegate()
$('body').on('click', '.dynamicallyCreatedElement', function () {
});
EDIT: Just so everyone gets it, when using delegate() the selector is the first argument and on on() it's the second one.
Upvotes: 4
Reputation: 7761
I have found the need to use this approach with on:
$('#container').on('click','.dynamicallyCreatedElement',function(){
console.log('click');
});
Upvotes: 2
Reputation: 94101
$('#closestStaticParent').on('click', '.dynamicallyCreatedElement' function(){
console.log('click');
});
Upvotes: 13