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,
.onwill only bind to existing elements unless you use a delegated event.Option #1
Bind to the
clickevent for the newly added elements in a callback (after the elements have been added to the DOM):Option #2
Use a delegated event that you bind to the container:
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
.rxinstead of binding directly todocument