Помогите со скриптом JS. Несколько модальных окон под лдним скриптом
Всем добра. Предупреждаю, что я в JS немного дерево :)
Вопрос: есть отличный скрипт для открытия модального окна и закрытия при помощи крестика и клика на пустом месте.
Скрипт нашел на просторах интернета.
Нужно на одной странице открывать три разных окна тремя разными кнопками (одновременно не получится, так как стилями не разрешено :) )
Я от своей скрипто-не грамотности просто дублировал код применяя разное название стилей и переменных, но ничего не работало, точнее работает открытие, но не закрывается окно, то одно, то другое. Одно кнопкой только закрывается, а если кликнуть за пределы модального окна, вообще ничего не закрывается.
Прошу помощи в реализации несколько окон на одной странице. Заранее спасибо.
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";}
}
Вот само окно:
<div id="myBtn">Кнопка открытия</div>
<div id="myModal" class="modal">
<div class="close">Закрыть</div>
</div>
Стиль:
.modal{
display: none;
position: fixed;
z-index: 9999;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.6);
}
Ответы (1 шт):
document.addEventListener("DOMContentLoaded", function () {
const openButtons = document.querySelectorAll(".open-modal");
const modals = document.querySelectorAll(".modal");
// Открытие по кнопке
openButtons.forEach((btn) => {
btn.addEventListener("click", () => {
const targetId = btn.getAttribute("data-target");
const modal = document.getElementById(targetId);
if (modal) modal.style.display = "block";
});
});
// Закрытие по "крестику"
modals.forEach((modal) => {
const closeBtn = modal.querySelector(".close");
if (closeBtn) {
closeBtn.addEventListener("click", () => {
modal.style.display = "none";
});
}
// Закрытие по клику вне окна
modal.addEventListener("click", (event) => {
if (event.target === modal) {
modal.style.display = "none";
}
});
});
});
.modal {
display: none;
position: fixed;
z-index: 9999;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.6);
}
.modal-content {
background-color: #fff;
margin: auto;
padding: 20px;
width: 80%;
max-width: 400px;
position: relative;
}
.close {
position: absolute;
right: 10px;
top: 10px;
font-size: 24px;
cursor: pointer;
}
<div class="open-modal" data-target="modal1">Открыть окно 1</div>
<div class="open-modal" data-target="modal2">Открыть окно 2</div>
<div class="open-modal" data-target="modal3">Открыть окно 3</div>
<div id="modal1" class="modal">
<div class="modal-content">
<div class="close">×</div>
<p>Модальное окно 1</p>
</div>
</div>
<div id="modal2" class="modal">
<div class="modal-content">
<div class="close">×</div>
<p>Модальное окно 2</p>
</div>
</div>
<div id="modal3" class="modal">
<div class="modal-content">
<div class="close">×</div>
<p>Модальное окно 3</p>
</div>
</div>