Reputation: 1450
I;m doing a lightbox tutorial from w3school (http://www.w3schools.com/howto/howto_js_lightbox.asp) what im trying to do is to close the lightbox when the user clicks on the screen, but only when it click outside of the img's.
With this piece of code that i'm using, it don't matter where the user clicks, it always closes the lightbox....is there a way to fix this.
$( 'body').on('click', function(event) {
closeModal();
});
Upvotes: 1
Views: 1050
Reputation: 1546
Keep the click listener registered on the body
like so:
$('body').on('click', function() {
closeModal();
});
And, as a simple solution, attach a click listener to the lightbox itself to capture and swallow any click events when it is the target.
$('.lightbox').on('click', function(e) {
e.stopPropagation();
});
stopPropagation
will prevent the event from bubbling up to other listeners, e.g. the document.body
. This will ensure that body
's listener won't fire.
Substitute .lightbox
with the unique selector for your lightbox container.
Upvotes: 1
Reputation: 5948
Try this:
$('body').on('click', function(event) {
closeModal();
});
$('#yourLightboxId').on('click', function(event) {
event.stopPropagation();
});
This will prevent that the click event reaches the lightbox's parents, which includes the body
.
Upvotes: 2
Reputation: 1995
$('.yourclassoflightbox').on('click', function(e) {
e.stopPropagation();
});
Upvotes: 1