I have a button
, which opens/displays a modal div
which it is clicked. Then, I want this div
to hide when the user clicks anywhere in the window outside the div
. So based on the code in this SO answer, I wrote the following SSCCE.
But it is NOT working. Once the modal is displayed, clicking outside it does not hide it. Nothing happens when I click outside the modal.
Where am I going wrong? How do I fix it?
Note: I have seen other questions dealing with the same requirement. I found the answered I have linked the best of all, and I tried it. The question is that why is This code not working?
$("button#open-modal-button").click(function() {
$(".modal").show();
});
$(document).mouseup(function(event) {
var modalContainer = $(".modal");
if ( ( !(modalContainer.is(event.target)) // if the target of the click is Not the modalContainer...
&& (modalContainer.has(event.target).length === 0) ) ) {// nor a descendant of the modalContainer
modalContainer.hide();
}
});
.modal {
width:100%;
height:100%;
background-color:rgba(0,0,0,0.4);
position:fixed;
z-index:1;
display:none;
left:0;
top:0;
}
.modal-content {
margin:5% auto;
background-color:#fefefe;
padding:20px;
border:1px solid #888;
width:40%;
height:70vh;
overflow:auto;
}
body {
box-shading:border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="open-modal-button">Open Modal</button>
<div class="modal">
<div class="modal-content">
<div class="modal-header">The header</div>
<div class="modal-content">
Some Content
</div>
</div>
</div>