I have a click function...
$('.rx').children().on('click',function(){alert('got here');});
My divs (50 of these div sets on the page)...
<div class="rx"><div id="'.$data_string.'" class="'.$button_image_class.'"><a href="#" ></a></div></div>
(each is a css sprite image button, which sends the $data_string in the id to a function "process_me". I've replaced the call to process_me with an alert('got here'); for this question. FYI the $button_image_class is variable, as a particular image is loaded depending on the member's account)
It all works beautifully, until I use pagination to load in more of the above divs (another 50, exactly the same bar $data_string, which is different in all the divs anyway).
The sprite image button links in the first 50 divs work how they should - clicking them prompts 'got here'. However, the links in the newly loaded div sets don't work.
I first guessed it's because the DOM isn't picking up the new elements, but .on('click',function()... is supposed to pick up future elements. So now I'm thinking it's something in
$('.rx').children().on('click',function(){alert('got here');});
that I've done wrong.
Anything sticking out there?
No, .on
will only bind to existing elements unless you use a delegated event.
Option #1
Bind to the click
event for the newly added elements in a callback (after the elements have been added to the DOM):
$.ajax({
...
}).done(function(){
$('.rx').children().on('click', function() {
alert('got here');
});
});
Option #2
Use a delegated event that you bind to the container:
$(document).on('click', '.rx > *', function() {
alert('got here');
});
Note: You probably want to replace the asterisk in the selector with an actual element type or class that matches the children. Using asterisk in selectors should be avoided when possible. Another improvement of the above is to use a parent that is closer to .rx
instead of binding directly to document
on() is not an alias of live(). It says "bind this future event to these children that I'm specifying of on element that I'm specifying that exists now"
$('.rx').on('click', '*', function(){alert('got here');});
but if it's the whole <div class="rx...>
that's being created dynamically not the elements inside of it
$(document).on('click', '.rx > *', function(){alert('got here');});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With