Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After injecting html by jquery, the event handlers doesn't work with/without delegate

Tags:

html

jquery

ajax

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 ?

like image 942
aacanakin Avatar asked Dec 12 '22 05:12

aacanakin


1 Answers

You need to bind the event handler to a common ancestor of the elements on which it should be triggered. For example, if your #element gets appended inside a div with an id of parent:

$("#parent").delegate(".commenticon", "click", function() {
    //Do stuff
});

This would be for an HTML structure like so:

<div id="parent">
    <div class="element">

    </div>
    <div class="element">

    </div>
</div>

The reason this works is that DOM events bubble up the tree from the point at which they originate. The delegate method 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 id values in the same document. Here I've changed your element ID values to class names instead.

Finally, if you are using jQuery 1.7+ you should use the on method instead. It will have the same effect, but notice the reversal of the first 2 arguments:

$("#parent").on("click", ".commenticon", function() {
    //Do stuff
};
like image 101
James Allardice Avatar answered May 17 '23 11:05

James Allardice