Как закрыть PopUp кликом на серую область?
У меня попап реализован на css.
И когда я произвожу событие клик, даже на самой форме она закрывается.
Я сделал пример моего попапа на CodePen
Когда открывается мой попап в URL добавляется строчка http://site/#modal
Вот один из последних примеров JS который я написал, другие я не буду писать, они всё-равно не работают так как нужно.
Быть может есть решение этой проблемы и на CSS.. Подскажите пожалуста
let writeForm = document.getElementById("write");
// Закрытие формы на серую область
document.onclick = function(e) {
if (e.target.id != writeForm) {
window.location.replace("#");
};
};
На всякий случай добавлю сюда реализацию PopUp на CSS
// Этот JS работает не корректно!!!
let writeForm = document.getElementById("write");
// Закрытие формы на серую область
document.onclick = function(e) {
if (e.target.id != writeForm) {
window.location.replace("#");
};
};
body {
display: flex;
justify-content: center;
margin-top: 100px;
}
#modal {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.9);
display: flex;
justify-content: center;
align-items: center;
}
.modal__window {
position: relative;
background-color: white;
padding: 4em 2em;
border-radius: 10px;
}
.modal__close {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
top: 10px;
right: 10px;
width: 25px;
height: 25px;
background-color: lightsteelblue;
border-radius: 10px;
}
#modal:not(:target) {
visibility: hidden;
opacity: 0;
}
.open {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
width: 208px;
height: 50px;
background-color: #5435a7;
border-radius: 100px;
&_a {
cursor: pointer;
font-size: 23px;
color: #ffffff;
text-decoration: none;
}
}
<div class="open">
<a class="open_a" href="#modal">Open Modal</a>
<div>
<div id="modal">
<div id="write" class="modal__window">
<a class="modal__close" href="#">X</a>
<h2>Please to meet you!</h2>
<p>Hello there, I am a nice Modal Window.</p>
</div>
</div>
Ответы (1 шт):
И когда я произвожу событие клик, даже на самой форме она закрывается.
А где в коде проверка на "саму форму"?
Из-за этого и будет закрываться, потому что если в форме есть что-то, оно будет равно true при условии e.target.id != writeForm, потому что оно не унаследует id="write" от родителя.
Добавьте в условие проверку на то, является ли нажатый элемент потомком в нужном элементе: !writeForm.contains(e.target)
Пример:
document.addEventListener('click', function(e) {
let el = document.querySelector('#write');
console.clear();
if(e.target !== el && !el.contains(e.target)) {
el.style.backgroundColor = 'green';
}
console.info(e.target !== el, !el.contains(e.target));
});
.modal__window {
width: 200px;
background: blue;
padding: 10px;
color: #fff;
}
.content {
display: block;
height: 50px;
padding: 10px;
background: red;
}
<div id="write" class="modal__window">
modal__window
<div class="content">
content
</div>
</div>