Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click event on selector returns child as target

I'm starting to lose my mind with Jquery today, I lookep up the other questions but nothing worked so far. I have the simple html structure (added dynamically in a for loop).

<div id="cell'+i+'" class="cell emptyCell">
     <div class="handle"></div>
     <div class="content"></div>
</div>

I'm using the "on" method to bind the "click event" of elements of class ".emptyCell" with a custom function.

$(document).on('click','.emptyCell', function(e){

    console.log(e.target.id);

});

But when the user clicks on the .content div (child of emptyCell), it catches the event, and the console prints "undefined" since .content elements don't have ids here.

How is that even possible ? Isn't the .on function supposed to bind elements of class .emptyCell only ?

Thanks for your help

like image 464
webaba Avatar asked Oct 18 '13 16:10

webaba


1 Answers

e.target refers to the actual element where the click happened(it can be handle or content elements), if you want to refer emptyCell then you can use this or e.currentTarget

$(document).on('click','.emptyCell', function(e){
    console.log(this.id);
    console.log(e.currentTarget.id);
});

Demo: Fiddle

like image 154
Arun P Johny Avatar answered Sep 21 '22 20:09

Arun P Johny