Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect clicks outside of a css modal? [duplicate]

Tags:

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?

like image 606
DomingoSL Avatar asked Nov 15 '14 21:11

DomingoSL


People also ask

How do you make a modal pop close when clicking outside?

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' .

Do not close modal popup when click outside?

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.

How can you tell if an element is clicked outside?

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.


1 Answers

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/.

like image 55
dfsq Avatar answered Sep 17 '22 13:09

dfsq