Reputation: 267059
I'm showing the user a modal/lightbox. The modal shows up and the rest of the page goes dim when the user clicks a button. Usual stuff.
However I want to do this. If the user clicks any element outside of the modal, I want the modal to go away and the page to return to normal.
How can this be done? I know I can set an onclick event for body, and then check if event target is my modal, but what if the user clicks on a link/textbox/button within the modal? In that case, target won't be the modal. How can I solve this?
Is there a way to check if the event target is contained with <div id="modal"></div>
, so if it is, I won't close the modal, and if not, that means user clicked outside the modal and I can close it?
Upvotes: 3
Views: 1095
Reputation: 5037
Another one approach:
var mouseOverModal = false;
$(document).click(function(e){
if ( ! mouseOverModal ){
// close modal
}
});
$('#modal').bind("mouseenter mouseleave", function(e){
mouseOverModal = ( "mouseenter" == e.type );
})
$('#open-modal-handler').click(function(){
// open modal
return false; // <- IMPORTANT
})
Upvotes: 1
Reputation: 5037
$("body").click(function(e){
if( ! $(e.target).closest("#modal").length ){
$('#modal').hide();
}
});
Upvotes: 1
Reputation: 206048
$(document).mouseup(function(e){
if(e.target.id !== 'modal' ){
$('#modal').hide();
}
});
$('#modal').mouseup(function(e){
e.stopPropagation(); // prevent mouseup propagate to underneath layers
});
Upvotes: 3
Reputation: 410
You could put a div under the modal that fills the entire space and attach your click handler to it.
Upvotes: 1