Reputation: 586
I am creating some dom elements according to some ajax response, which I want to add js event listeners to them. The following is my code :
$output = "<div><div class='recipients'><ul>";
foreach($contacts as $contact){
$output .= "<li>
<div>
<input class='contact-checkbox' type='checkbox' checked/>
<span>{$contact['dnr']['tel_no']}</span>
</div>
</li>";
}
$output .="</ul></div></div>";
The above output is used here as shown (ie. $(list).html() is returning the above generated markup.)
$("<div id='" + filter_id + "' class='filter toggler'>" + filter_id + $(list).html() + "</div>").appendTo($('#recipient-list'));
After appending the element, I call a method 'bind_functions()' which binds prepared event handlers as follows :
function bind_functions(){
$('.toggler').click(function(e){
$(this).toggleClass('active');
//e.stopPropagation();
});
$('.recipients').click(function(e){
e.stopPropagation();
});
}
The above code simply creates a a div which is wrapped around an unordered list <ul>
with its child lists <li>
. This element is created more than once, with the purpose of creating multiple filters. On click, they slide down to show their respective <ul><li>
elements.
This all seems to work fine until you add more than one.. WHat happens is(very strange IMO), upon creating the element the first time, the event is binded and it works, when adding the second, the second element works, but the first element does not work anymore. If I add the third element, then the 1st and the 3rd(last added) elements, are listening to the event and work, but the 2nd doesnt. As you might imagine, if I add the 4th element, the 2nd and 4th element will listen to the event, whilst the 1st and third are back to not working..
What could be the cause of this. How can an element be binded to and event listener at one point, and not be, in another point in time. The generated markup all seems fine but I will also provide it here, perhaps I am missing something .
Here it is
<div id="Any-Female-Any" class="filter toggler">Any-Female-Any
<div class="recipients">
<ul>
<li>
<div>
<input class="contact-checkbox" type="checkbox" checked="">
<span>441895324</span>
</div>
</li>
<li>
<div>
<input class="contact-checkbox" type="checkbox" checked="">
<span>449185147</span>
</div>
</li>
</ul>
</div>
</div>
This is whats generated in dom tree when inspecting in google
Upvotes: 0
Views: 105
Reputation: 152276
You can try with:
$(document)
.on('click', '.toggler', function(){
// toggler click
})
.on('click', '.recipients', function(){
// recipients click
})
;
There will be no need to create an call bind_functions
function and it will handle new DOM elements created during the runtime.
Upvotes: 1
Reputation: 49
You would be much better off by using bind feature of jQuery: https://api.jquery.com/bind/
Upvotes: 0