4

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)

aviraldg
  • 9,531
  • 6
  • 41
  • 56

2 Answers2

9

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.

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
  • 1
    Actually, there are two types of attaching to a DOM event in JavaScript: [capturing](http://www.quirksmode.org/js/events_order.html) and [bubbling](http://stackoverflow.com/questions/2661199/event-capturing-vs-event-bubbling). (Note: Links are not directly related to the link text) – Hello71 Nov 13 '10 at 04:13
  • @Hello71: I knew that. It's just that capturing isn't used often because it doesn't work in IE 8 or less. Internet Explorer does support a limited form called "mouse capturing" though: http://msdn.microsoft.com/en-us/library/ms536742%28VS.85%29.aspx – PleaseStand Nov 13 '10 at 04:21
0

Well, I'd do something like this:

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

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

Peter C
  • 6,219
  • 1
  • 25
  • 37