0
I made a modal and I need it to be closed by clicking outside of it or the close button. I’ve tried to do with onblur only it doesn’t work, it’s only for tag input. How should I do?
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>
I didn’t quite understand addeventlistener and target
– nelson450
@nelson450 you know what makes the
addEventListener
?– Sergio
No, and I don’t know the target very well
– nelson450
@nelson450 the
addEventListener
record in the event that you want to be notified when a given event happens. The event you want to "listen" you pass as the first argument and the function running you pass as the second argument. Does it make sense? (I’ll explain more if you understand)– Sergio
Yes, and the e.target?
– nelson450
And onblur only works for forms?
– nelson450
@nelson450 ok, so this function always takes an argument, passed by Javascript. This argument is the event, an object, which has the property
target. Essa propriedade é o elemento onde o clique aconteceu. Neste caso o
addeventlisteneré associado ao
modal, então o
thisdentro dessa função é **sempre** o modal, mas o
e. target` is the element (within the modal or itself) where the click took place. It makes sense?– Sergio
Okay, I get it now, thank you
– nelson450