Charles Yeung
Charles Yeung

Reputation: 38805

Is it possible to check which "children" DIV was clicked

If I write the listener as below,

$('.parent').bind('click', function() {
//...
})

<div class="parent">
    <div class="children1"></div>
    <div class="children2"></div>
    <div class="children3"></div>
</div>

For example I clicked children2, Is it possible to check which "children" DIV under parent was clicked?

Thanks

Upvotes: 3

Views: 196

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

Yes, you can look at e.target (change your handler to accept e as an argument), possibly using closest to get the first div ancestor of the actual element clicked (in case those child divs have descendants).

$('.parent').bind('click', function(e) {
    // Here, `e.target` is the DOM element where the click occurred
    var div = $(e.target).closest('div');
});

Live Example | Source

Alternately, if you only want the handler to fire when one of the children is clicked, you can use event delegation via delegate or on:

$('.parent').delegate('div', 'click', function(e) {
    // Here, `this` is the child div that was clicked
});

// or

$('.parent').on('click', 'div', function(e) {
    // Here, `this` is the child div that was clicked
});

Live Example | Source

Note that the order of args is different between delegate (which I prefer for the clarity) and on (which it seems like everyone else prefers).

Upvotes: 8

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

Working Demo

You can look at the target of the event. Here the event is e.

$('.parent').bind('click', function(e) {
   console.log(e.target);
});

Upvotes: 3

Michael Bialas
Michael Bialas

Reputation: 76

You should use

$('.parent').on('click', 'div', function() {
// ...
});

.on() should be used instead of .bind(). this references the clicked div in the event-handler.

Upvotes: 0

Talha Akbar
Talha Akbar

Reputation: 10030

e.target.className will get class name of div on which event fired.

$('.parent').bind('click', function(e) {
   if(e.target.className.indexOf('children') != -1) { // <-- Perform function only if any child is clicked
     // do something
   }
})

Upvotes: 0

Related Questions