I have a list of <div> s with same html but different values inside html. The hierarchy is the following ;
<div id="element">
<div class="likecomm">
<a class="commenticon" href="#">...some value according to the returning value...</a>
</div>
</div>
<div id="element">
<div class="likecomm">
<a class="commenticon" href="#">...some value according to the returning value...</a>
</div>
</div>
In an event, I inject html to the top of the list which is another <div id="element> ... </div>
I have the following event handler for comment icon click;
$('.commenticon').click(function(){
$(this).closest('.actionframe').next('nav').slideToggle(300);
return false;
});
It works correct until I insert the new <div id="element> ... </div>. The comment icon click event handler doesn’t match. I searched about that problem, all were saying that .delegate() should be used.
My problem is I don’t know where to use the delegate function. Before, I get the results from ajax in order to inject the <div id="element> ... </div> , I used .delegate() function in ajax call that injects html.
$.ajax({
success:function(data) {
var html=... // the necessary div html binded with data
// prepend function call()
$('.likecomm').delegate(".commenticon","click" , function() {
$(this).closest('.actionframe').next('nav').slideToggle(300);
return false;
});
}
});
Currently, it doesn’t work. So, any ideas how to make this thing work ?
You need to bind the event handler to a common ancestor of the elements on which it should be triggered. For example, if your
#elementgets appended inside adivwith anidofparent:This would be for an HTML structure like so:
The reason this works is that DOM events bubble up the tree from the point at which they originate. The
delegatemethod captures the event at an ancestor element and checks whether or not it originated at an element matching the selector.Also note that it’s invalid to have duplicate
idvalues in the same document. Here I’ve changed yourelementID values to class names instead.Finally, if you are using jQuery 1.7+ you should use the
onmethod instead. It will have the same effect, but notice the reversal of the first 2 arguments: