@JyriG

Конфликт в коде для модальных окон, как исправить?

Привет)

На странице сайта есть три кнопки вызывающие модальное окно: В меню, в описании товара и в футере.
Дело в том что между тремя скриптами для разных окон возникает конфликт и высвечивается то окно, которое является последним. Вместо тысячи слов вставлю кусочки кода)

Код первой заявки:
<button id="Launch-modal__BTN" href="#">Заказать звонок!</button>
<div id="Menu__request" class="modal">
<!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <div class="Menu__request_heading">
      Заказать звонок
    </div>
    <form class="Menu__request_form" id="form" action="sender.php">
        <input type="hidden" name="project_name" value="Сайт “СвятоГор”">
<input type="hidden" name="admin_email" value="sekret)">
<input type="hidden" name="form_subject" value="С заявки на звонок">
        <input type="text" name="Имя клиента" placeholder="Ваше имя и фамилия" required>
        <input type="tel" name="Телефон" placeholder="Ваш телефон" required>
        <input name="sendMail" type="submit" class="Submit__BTN">
      </form>
  </div>
</div>
<script>// Get the modal
var modal = document.getElementById('Menu__request');

// Get the button that opens the modal
var btn = document.getElementById("Launch-modal__BTN");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}</script>
    </div>
  </div>
,
вторая заявка:
<div class="dostavka__button">
            <button id="Launch-modal__BTN6">Заказать!</button>
            <span class="certified">Товар сертифицирован</span>
          </div>
          <div id="Menu__request6" class="modal">
<!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <div class="Menu__request_heading">
      Заказать ОПАЛУБКУ ПЕРЕКРЫТИЙ
    </div>
    <form class="Menu__request_form" id="form" action="sender.php">
<input type="hidden" name="project_name" value="Сайт “СвятоГор”">
<input type="hidden" name="admin_email" value="jyri.gromyko3003@gmail.com">
<input type="hidden" name="form_subject" value="С страницы Рамных лесов">
        <input type="text" name="Имя клиента" placeholder="Ваше имя и фамилия" required>
        <input type="tel" name="Телефон" placeholder="Ваш телефон" required>
        <input type="tel" name="email" placeholder="Ваш email" required>
        <textarea placeholder="Сообщение.." name="Сообщение"></textarea>
        <input name="sendMail" type="submit" class="Submit__BTN">
      </form>
  </div>
</div>
<script>// Get the modal
var modal = document.getElementById('Menu__request6');

// Get the button that opens the modal
var btn = document.getElementById("Launch-modal__BTN6");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}</script>
        </div>
      </div>      
    </div>

Третья заявка в футере:
<div class="Footer__phone_number">
        +7 8812 308 88 84
        </div> <br>
            <a href="#footer" id="Launch-modal__BTN2">Заказать звонок!</a>
    </div>
    <script>// Get the modal
var modal = document.getElementById('Menu__request');

// Get the button that opens the modal
var btn = document.getElementById("Launch-modal__BTN2");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}</script>

Вот что всплывает при нажатии любую "модальную" кнопку если ничего не модифицировать:
5a859d0f41b03084076719.png
И вот такое если закомментировать скрипт для кнопки в футере:
5a859da5aef1c858964569.png

Что делать, помогите!
  • Вопрос задан
  • 110 просмотров
Пригласить эксперта
Ответы на вопрос 1
villiwalla
@villiwalla
HTML-верстка
Нужно не плодить один и тот же код для каждой модалки. Напишите ваш код так:
1. Вещание на все элементы с классом Х событие клик
2. Событие клик вызывает функцию открытия нужной модалки. Нужную модалку можно определить в пункте 1.
3. На элементах предназначенных для закрытия модалки надо повесить событие вызывающего функцию закрытия текущий модалки. Какую модалку закрыть можно узнать в момент всплытия события для закрытия
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы