Using .live() :
<input type="button" value="button" />
$(":input[type=button]").live({
click: function() {
$(this).after('<input type="button" value="new" />');
},
mouseover: function() {
//do something
},
mouseout: function() {
//do something
}
});
DEMO : http://jsfiddle.net/F9gC4
Here delegation works fine. If we click ‘button’ or ‘new’, new button element will be created.
Using .on() :
<input type="button" value="button" />
$(":input[type=button]").live({
click: function() {
$(this).after('<input type="button" value="new" />');
},
mouseover: function() {
//do something
},
mouseout: function() {
//do something
}
});
DEMO : http://jsfiddle.net/CB8fh
Here delegation doesn’t work. ‘new’ button click doesn’t create element(can’t fire)
So how can we use .on() multiple event handlers with delegation(future element)?
Is this possible?
Try this code:
For delegation to work with created/future elements you need to attach the event to document and use the ‘selector’ argument of the .on function to target the event. Not tested, but in theory should work! See documentation for the on function and also the documentation for live has a section on moving to the .on function.
Edit just wanted to add, as @Joy said in his answer, you don’t need to attach to
document, the closer to the target element you delegate to the better (although you need to be sure that element will not be affected by ajax/dom changes that might remove the event handler).