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); }
http://jsfiddle.net/c89Ls0av/
Is there a clean and reliable way to detect when somebody clicks outside of the modal?
closest(". modal") , then call the closeModal() function. When the closeModal() function is called, it selects the . modal class selector and hides it with display = 'none' .
here in the above code data-backdrop="static" data-keyboard="false ", HTML attributes will help you to prevent closing the modal. Data-keyword="false" is to prevent closing modal while clicking Esc button, while data-backdrop="static" , allows you keep modal pop-up opened when clicking on Gray area.
To detect click outside element with JavaScript, we can use the element's contains method. const specifiedElement = document. getElementById("a"); document. addEventListener("click", (event) => { const isClickInside = specifiedElement.
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!'); } });
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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With