Jasper
Jasper

Reputation: 5238

Click not fired for child element

Demo http://jsfiddle.net/tsxb8/

$('.parent').on('click', function() {
   alert(1); 
});
$('.child').on('click', function() {
   alert(2); 
});

I need to launch some code, which is attached to a child element, when a parent element is clicked.

As I can see, childs click handler isn't fired when user clicks on a parents area (darker grey, alert = 1), which isn't a part of a childs area (lighter grey, alert = 2).

How do I fix this?

Upvotes: 1

Views: 1509

Answers (1)

Barmar
Barmar

Reputation: 780724

Trigger the click on the child explicitly in the parent handler:

$('.parent').click(function() {
    alert(1);
    $(this).find('.child').click();
});

$('.child').click(function(e) {
    e.stopPropagation(); // Prevent bubbling to parent, to avoid loop
    alert(2);
});

DEMO

Upvotes: 6

Related Questions