I have a complicated nested form (Ryan Bates’ version) with .live() attached to some of the dynamically generated elements, which I’m now transitioning over to .on() along with an upgrade from Jquery 1.4 to 1.7.
Here’s a sample of one of the ~22 changes:
# old version with .live()
$('.options .image').live('click', function(){
console.log('clicked .options')
})
# new version with .on()
$('.options').on('click', '.image', function(){
console.log('clicked .options')
})
The changes work perfectly well for the form elements that already exist but they are failing for any nested elements that are dynamically created afterwards. Hence, it’s working more like Jquery’s bind than live. Do you know what might be going on here?
Due to the exceeding complexity of the code and lots of partials I’m leaving it out for now (hoping you might have a hunch!). Thanks.
As per 3nigma’s comment but modified with your original selector, this will work:
However, I don’t think setting document as listener is usually the way to go. In your original version with
.live()you are selecting.imagenodes within the.optionsnode.But the question doesn’t say which parts are loaded dynamically. I suspect that
.optionsis also part of the content that’s loaded dynamically. The first selector when using.on()for delegating listeners has to be something that is NOT destroyed:#someWrapperdoesn’t need to be a new wrapper element, it can be any ancestor (what some people call a “parent”… but that’s a misnomer since it can be a grandparent or great-grandparent or whatever!) that is not destroyed. The closer to the target selector (.options .image) the better.