Toddles
Toddles

Reputation: 31

Void JS Click in Pop-up area of "lightbox"

I'm making a super simple "lightbox" that pops up with a dialog box, and a dimmed background.

My problem is, I want the overlay to disappear when the user clicks on the dimmed background, but not if they click in the dialog box area.

My approach so far has been this:

I added a class with "display:none;" to the the wrapper so it would disappear if clicked. Of course, if you click in the #dialogBox this makes the overlay disappear as well. Is there any way to tell it to return the click false in the dialogBox area? Or a better way to approach this?

<div id="overlay" onclick="$(this).addClass('displayNone');">
    <div id="dialogBox">
        <p>Lorem ipsum</p>
</div>
</div><!-- /#overlay -->

Thank you!

Upvotes: 1

Views: 124

Answers (2)

Ian
Ian

Reputation: 50905

Remove the inline onclick attribute/handler, and bind the event in JavaScript:

$("#overlay").on("click", function (e) {
    if (!$(e.target).closest("#dialogBox").length) {
        $(this).addClass('displayNone');
    }
});

DEMO: http://jsfiddle.net/A7rNE/

This will check if the click came from anywhere within the #dialogBox element - if it didn't (note the ! in the if statement), it runs the .addClass() part.

References:

Upvotes: 2

Jason P
Jason P

Reputation: 27012

This should prevent the click event from bubbling up to whatever element handles closing the lightbox:

$('#dialogBox').click(function(e) {
    e.stopPropagation();
})

Upvotes: 1

Related Questions