Zak
Zak

Reputation: 2698

How do you attach a jquery event only to the outer div?

I'm working on a jQuery light box. It works great, but I'd like to add another feature: I'd like the box to close when the surrounding, "dimmer", div is clicked, but not when the main one is.

To clarify, I have two divs: div A and div B. Div A has a semi-transparent background image, and covers the entire screen (it is absolutely positioned). Div B is smaller, and inside of div A (also absolutely positioned) and has the main content of the light box. Is it possible to attach a click event to div A (outer) that does not fire if div B (the inner one) is clicked?

Thanks!

Upvotes: 2

Views: 823

Answers (2)

alex
alex

Reputation: 490283

The best way to achieve that is...

$('#your-light-box').click(function(event) {
   event.stopPropagation();
});

$(document).click(function() {
  closeLightbox();
});

Upvotes: 4

Arun
Arun

Reputation: 3077

In the click event of div B, return false. This will ensure the event does not bubble and trigger the click of the parent elements (div A)

Even if you are not doing anything on click of Div B, just return false

$("#divB").click(function(){
    return false;
});

Upvotes: 4

Related Questions