Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get clicked element in delegated event with jQuery

I have some elements that I add to the DOM after the page has been loaded. And I'd like to perform some actions when I click on them. I'm using the delegation with jQuery but I don't know how to get the clicked element when I'm in the fonction ($(this) refers in this case to the parent)

<div id="parent">
    <div class="child">
        <div class="hidden"></div>
    </div>
    <div class="child">
        <div class="hidden"></div>
    </div>
</div>

<script>
$('#parent').click('.child', function(){
    $(this).find('.child').toggleClass("hidden displayed")
});
</script>

Let's say I want to toggle the inner div from "hidden" to "displayed" when I click on the "child" div. Currently when I click on the first "child" div, the two "hidden" div will be toggled, and I want to be toggled only the one in the div I clicked.

like image 361
ValLeNain Avatar asked Dec 01 '22 01:12

ValLeNain


2 Answers

Use e.target to find out which element the event originated on.

$('#parent').on('click', '.child', function(e){
    $(e.target).toggleClass("hidden displayed")
});

I also fixed the code a bit - you need to use .on for delegated events. (Mentioned by Barmar.)

like image 75
Scimonster Avatar answered Dec 04 '22 11:12

Scimonster


You need to use .on() to delegate events. As the documentation says:

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector.

So it should be:

$('#parent').on('click', '.child', function() {
    $(this).toggleClass("hidden displayed");
};

Your use of .click('.child', function...) does not do delegation. It matches the function signature:

.click(eventData, handler)

described here. So it's just binding to the parent, not delegating to the child, that's why you get the wrong value in this.

like image 23
Barmar Avatar answered Dec 04 '22 10:12

Barmar