How to close a modal when clicking outside it?

0

I made a modal and need it to be closed by clicking outside it or the close button. I already tried to do with onblur only that it does not work, it only serves for tag input. How should I do it?

function abre() {
			document.getElementById('modal').style.display = 'block';
}
function fecha() {
			document.getElementById('modal').style.display = 'none';
}
#modal{
			display: none;
			position: fixed;
			z-index: 1;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.5);
		}
		#modalcont{
			width: 400px;
			height: 300px;
			border: 2px solid black;
			position: relative;
			left: 35%;
			top: 20%;
			background-color: lightblue;
			text-align: center;
		}
		#close{
			position: absolute;
			border-radius: 50%;
			font-size: 26px;
			padding: 10px;
			background-color: lightgreen;
			text-align: center;
			right: -10px;
			top: -20px;
			cursor: pointer;
		}
<button onclick="abre()">abra o modal!</button>
	<div id="modal" onblur="fecha()">
		<div id="modalcont">
			<a onclick="fecha()" id="close">X</a>
			<p>teste desse modal</p>
		</div>
	</div>
    
asked by anonymous 19.08.2017 / 15:16

1 answer

2

I gave similar answers here and here . In this case it is even simpler since you have an element working as overlay where you only need to detect if you hear a click on it with

modal.addEventListener('click', function(e) {
  if (e.target == this) fecha();
});

Example:

var modal = document.getElementById('modal');
modal.addEventListener('click', function(e) {
  if (e.target == this) fecha();
});

function abre() {
  modal.style.display = 'block';
}

function fecha() {
  modal.style.display = 'none';
}
#modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

#modalcont {
  width: 400px;
  height: 300px;
  border: 2px solid black;
  position: relative;
  left: 35%;
  top: 20%;
  background-color: lightblue;
  text-align: center;
}

#close {
  position: absolute;
  border-radius: 50%;
  font-size: 26px;
  padding: 10px;
  background-color: lightgreen;
  text-align: center;
  right: -10px;
  top: -20px;
  cursor: pointer;
}
<button onclick="abre()">abra o modal!</button>
<div id="modal" onblur="fecha()">
  <div id="modalcont">
    <a onclick="fecha()" id="close">X</a>
    <p>teste desse modal</p>
  </div>
</div>
    
19.08.2017 / 15:31