How to detect clicks outside of a css modal? [duplicate]
Im using a very simple and clean code to render a modal in my page:
<div class="modal">I'm the Modal Window!</div>
.modal {
/* some styles to position the modal at the center of the page */
position: fixed;
top: 50%;
left: 50%;
width: 300px;
line-height: 200px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
background-color: #f1c40f;
text-align: center;
/* needed styles for the overlay */
z-index: 10; /* keep on top of other elements on the page */
outline: 9999px solid rgba(0,0,0,0.5);
}
Is there a clean and reliable way to detect when somebody clicks outside of the modal?
Probably the simplest way is to bind click event to body and see if it comes from the element (e.target) which has parent (walk up the tree with closest
method) .modal
:
$(document).click(function(e) {
if (!$(e.target).closest('.modal').length) {
alert('click outside!');
}
});
Demo: http://jsfiddle.net/c89Ls0av/4/
By the way, overlay made with outline
is an interesting idea, but it’s not real overlay, as it still allows to interact with underlying page elements. Here is an example of the overlay made with div container covering entire page: http://jsfiddle.net/c89Ls0av/5/. This one will prevent page interaction when modal is visible.
And here is an example of how open/close functionality can be use together: http://jsfiddle.net/c89Ls0av/7/.
WithOut jQuery
document.addEventListener('click', function (e) {
if(e.target.className === 'modal'){
alert('clicked in');
}else {
alert('clicked out');
}
}, false);
check it out:
http://jsbin.com/totonopili/1/edit?html,css,js,output
With the help of a javascript framework this is quite easy.
Follow these steps:
- Attach a click event to the document which closes or hides the modal.
- Attach a separate click event to the window which stops click propagation.
Example:
$('html').click(function(){
$('.modal').hide();
});
$('.modal').click(function(e){
e.stopPropagation();
});
http://jsfiddle.net/c89Ls0av/3/
Warning! Stopping propagation can introduce strange behaviour
Dfsq answer will work fine.. but if you want something to do with dialog boxes you may have a look at jQuery ui dialog boxes. It gives you many options with dialog boxes which you can configure as per your needs.