aviraldg
aviraldg

Reputation: 9154

How to check for a click in a parent element, but not in the child?

Code:

HTML

<!-- snip -->
<div class="parent" id="parent">
    <div class="child" id="child">
    </div>
</div>
<!-- snip -->

Javascript

/* snip */
$(function () {
    $("#parent").click(function () {
        alert("This dialog should only show up if the parent is clicked.");
    });
});
/* snip */

(This is just the basic structure of the actual code... some things are different in the actual code eg. the child is a jQuery UI Draggable element)

Upvotes: 4

Views: 3374

Answers (2)

Peter C
Peter C

Reputation: 6307

Well, I'd do something like this:

$("#child").click(function() { });

Though that seems a bit ugly, it's guaranteed to work, I think.

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32052

The way JavaScript/DOM events work is that they "bubble" up from children to parents. So you just need to stop that at the child element:

$('#child').click(function(event) {
    event.stopPropagation();
});

See the jQuery documentation for .click() for more information. Alternatively, you could check to see what the originating element is within the parent's event handler using event.target.

Upvotes: 9

Related Questions