I am trying to register a event on elements like this:
$(document).ready(function() {
$('.classname').change(function(){
alert ('This line is never triggered');
});
});
But the problem is that .classname elements are later loaded into the dom by ajax. So, how do I correctly register an event in this case? Is it possible to do it only once (I mean, not every time the new element appears?)
Further to the answers suggesting that you use
live(), it’s also possible to usedelegate(), for example:For
delegatethe element to assign the selector (.classname')to, in this case the$('form')must exist in the DOM at the time of assignment.Edited to note that the following section (following the next ‘edited’ until the ‘Reference’) is wrong:
JS Fiddle demo.
Calling
stopPropagation()on an element between the element selected by thedelegate()selector and the target to which the event isdelegate()-d does somewhat predictably (though I hadn’t realised this before) prevent the delegation from occurring.Edited in response to question, in comments, from OP:
Not according to the jQueryAPI (the entry is linked-to below):I’ve not tried/verified this as yet, but it seems that even if an element that sits between the target element ($('.classname')) and thedelegate()-d element ($('form')) callsstopPropagation()it shouldn’t have an adverse effect on thedelegate().Reference:
delegate().