Adam
Adam

Reputation: 3518

Jquery lightbox click :not

I'm trying to get a :not click event with jquery. Essentially I'm trying to build a lightbox. Works fine, but I would like it to close ONLY if the black space is clicked. If the image is clicked lightbox should not hide.

Please see the example: http://jsfiddle.net/nrUCc/7/ I have tried this: (line 42 in the js column)

 $('#lightbox').not('#lightbox img').click(function(e){
        $(this).css('display','none');
 })

..but still it triggers when I click on the image.

Any suggestions? thanks

Upvotes: 4

Views: 488

Answers (1)

billyonecan
billyonecan

Reputation: 20260

You can compare the target element against this:

$('#lightbox').click(function(e) {
    if (e.target === this) { 
        $(this).css('display','none');
    }
});

e.target is the element which triggered the click handler, this is the #lightbox element. So basically you're saying only trigger the click handler when #lightbox has been clicked. This will also prevent any other child elements of #lightbox from triggering the above click handler.

Here's a fiddle


An alternative would be to add another click handler to the #lightbox > img elements, and simply stop the click event from propagating and triggering the above:

$('#lightbox > img').click(function(e) {
    e.stopPropagation();
});

Upvotes: 1

Related Questions