How to make modal close on click outside
This seemed to be the code that worked out for me in the end:
$(document).click(function (e) {
if ($(e.target).is('#openModal')) {
$('#openModal').fadeOut(500);
}
});
$("#modalNo").click(function () {
$("#openModal").fadeOut(500);
});
$(".close").click(function () {
$("#openModal").fadeOut(500);
});
$(".close-circle").click(function () {
$("#openModal").fadeOut(500);
});
Adding to this for future readers.
Another way to dismiss the modal when clicking outside involved taking advantage of the bubbling nature of the javascript events.
In a typical modal HTML structure
<body>
<div id="root">
-- Site content here
</div>
<div id="modal-root">
<div class="modal"></div>
</div>
</body>
clicking on .modal
will cause the click event to propagate like this .modal -> #modal-root -> body
while clicking outside the modal will only go through #modal-root -> body
.
Since we can stop the propagation of click events completely, and if that does not interfere with any other code, we only need to listen for click events in both .modal
and #modal-root
. A "modal-root" click will dismiss the modal, and a "modal" click will stop propagating the click event so never reaches the "modal-root".
For extra clarity, here's the code working in codepen.io: https://codepen.io/nbalaguer/pen/PVbEjm
Use the parent node #openModal
(container) instead of #popUpForm
(form) :
$('body').click(function (event)
{
if(!$(event.target).closest('#openModal').length && !$(event.target).is('#openModal')) {
$(".modalDialog").hide();
}
});
This is working for me: I have an image inside of the modal window, so if someone click outside the image (centered):
html code:
<div id="modal_div"><img id="image_in_modal_div" src="image.jpg" /></div>
ccs code:
#modal_div {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: transparent;
}
#image_in_modal_div {
left: 50%;
top: 30%;
position: absolute;
}
mixed jquery and javascript code:
$( document ).ready(function() {
$("#element_that_opens_modal").click(function(){
$("#modal_div").show();
});
window.onclick = function(event) {
if (event.target.id != "image_in_modal_div") {
$("#modal_div").hide();
}
}
});