Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 01.03.2024, 20:16
Новичок на форуме
Отправить личное сообщение для Лена Лапина Посмотреть профиль Найти все сообщения от Лена Лапина
 
Регистрация: 19.02.2016
Сообщений: 9

Несколько popup окон на чистом JS
Доброго времени суток!
Помогите пожалуйста сделать несколько popup окон с разным содержимым. Вот один работает замечательно - https://codepen.io/webdevtips-ru/pen/OJmydVd

<div class="wrapper">
    <a href="#" class="open-popup">Открыть попап</a>
    <a href="#" class="open-popup">Открыть попап</a>
    <a href="#" class="open-popup">Открыть попап</a>
</div>

<div class="popup__bg">
    <form class="popup">
        <svg class="close-popup" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#2982ff" d="M23.954 21.03l-9.184-9.095 9.092-9.174-2.832-2.807-9.09 9.179-9.176-9.088-2.81 2.81 9.186 9.105-9.095 9.184 2.81 2.81 9.112-9.192 9.18 9.1z"/></svg>
        <label>
            <input type="text" name="name">
            <div class="label__text">
                Ваше имя
            </div>
        </label>
        <label>
            <input type="tel" name="tel">
            <div class="label__text">
                Ваш телефон
            </div>
        </label>
        <label>
            <textarea name="message"></textarea>
            <div class="label__text">
                Ваше сообщение
            </div>
        </label>
        <button type="submit">Отправить</button>
    </form>
</div>  <div class="wrapper">
    <a href="#" class="open-popup">Открыть попап</a>
    <a href="#" class="open-popup">Открыть попап</a>
    <a href="#" class="open-popup">Открыть попап</a>
</div>

<div class="popup__bg">
    <form class="popup">
        <svg class="close-popup" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#2982ff" d="M23.954 21.03l-9.184-9.095 9.092-9.174-2.832-2.807-9.09 9.179-9.176-9.088-2.81 2.81 9.186 9.105-9.095 9.184 2.81 2.81 9.112-9.192 9.18 9.1z"/></svg>
        <label>
            <input type="text" name="name">
            <div class="label__text">
                Ваше имя
            </div>
        </label>
        <label>
            <input type="tel" name="tel">
            <div class="label__text">
                Ваш телефон
            </div>
        </label>
        <label>
            <textarea name="message"></textarea>
            <div class="label__text">
                Ваше сообщение
            </div>
        </label>
        <button type="submit">Отправить</button>
    </form>
</div>



Код:
* {
    box-sizing: border-box;
}

body {
    margin: 0;
    padding: 0;
    font-family: 'Montserrat', sans-serif;
}

.wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    width: 100%;
    height: 100vh;
}

.open-popup {
    display: inline-block;
    padding: 15px 30px;
    text-transform: uppercase;
    background: #2982ff;
    color: #fff;
    text-decoration: none;
    font-weight: 500;
    border-radius: 5px;
}

.popup__bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: rgba(0,0,0,0.5);
    opacity: 0;
    pointer-events: none;
    transition: 0.5s all;
}

.popup__bg.active {
    opacity: 1;
    pointer-events: all;
    transition: 0.5s all;
}

.popup {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 400px;
    padding: 25px;
    transition: 0.5s all;
}

.popup.active {
    transform: translate(-50%, -50%) scale(1);
    transition: 0.5s all;
}

.close-popup {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
}

.popup label {
    width: 100%;
    margin-bottom: 25px;
    display: flex;
    flex-direction: column-reverse;
}

.popup .label__text {
    font-size: 14px;
    text-transform: uppercase;
    font-weight: 500;
    color: #cfd0d3;
    margin-bottom: 5px;
}

.popup input {
    height: 45px;
    font-size: 18px;
    border: none;
    outline: none;
    border-bottom: 1px solid #cfd0d3;
}

.popup input:focus {
    border-bottom: 1px solid #2982ff;
}

.popup input:focus + .label__text {
    color: #2982ff;
}

.popup textarea {
    resize: none;
    width: 100%;
    height: 150px;
    border: none;
    outline: none;
    border-bottom: 1px solid #cfd0d3;
    font-size: 18px;
    padding-top: 5px;
}

.popup textarea:focus {
    border-bottom: 1px solid #2982ff;
}

.popup textarea:focus + .label__text {
    color: #2982ff;
}

.popup button {
    width: 100%;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 18px;
    border: 2px solid #2982ff;
    background: #2982ff;
    cursor: pointer;
    text-transform: uppercase;
    transition: 0.5s all;
}

.popup button:hover {
    background: #fff;
    color:#2982ff;
    transition: 0.5s all;
}

let popupBg = document.querySelector('.popup__bg');
let popup = document.querySelector('.popup');
let openPopupButtons = document.querySelectorAll('.open-popup');
let closePopupButton = document.querySelector('.close-popup');

openPopupButtons.forEach((button) => {
    button.addEventListener('click', (e) => {
        e.preventDefault();
        popupBg.classList.add('active');
        popup.classList.add('active');
    })
});

closePopupButton.addEventListener('click',() => {
    popupBg.classList.remove('active');
    popup.classList.remove('active');
});

document.addEventListener('click', (e) => {
    if(e.target === popupBg) {
        popupBg.classList.remove('active');
        popup.classList.remove('active');
    }
});
Ответить с цитированием
  #2 (permalink)  
Старый 01.03.2024, 22:08
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,733

Немного изменил ваш код:
<div class="wrapper">
    <a href="#" class="open-popup" data-popup-id="1">Открыть попап</a>
    <a href="#" class="open-popup" data-popup-id="2">Открыть попап</a>
    <a href="#" class="open-popup" data-popup-id="3">Открыть попап</a>
</div>

<div class="popup__bg" data-popup="1">
    <form class="popup">
        <svg class="close-popup" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#2982ff" d="M23.954 21.03l-9.184-9.095 9.092-9.174-2.832-2.807-9.09 9.179-9.176-9.088-2.81 2.81 9.186 9.105-9.095 9.184 2.81 2.81 9.112-9.192 9.18 9.1z"/></svg>
        <label>
            <input type="text" name="name">
            <div class="label__text">
                Ваше имя
            </div>
        </label>
        <label>
            <input type="tel" name="tel">
            <div class="label__text">
                Ваш телефон
            </div>
        </label>
        <label>
            <textarea name="message"></textarea>
            <div class="label__text">
                Ваше сообщение
            </div>
        </label>
        <button type="submit">Отправить</button>
    </form>
</div>

<div class="popup__bg" data-popup="2">
    <div class="popup">
        <svg class="close-popup" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#2982ff" d="M23.954 21.03l-9.184-9.095 9.092-9.174-2.832-2.807-9.09 9.179-9.176-9.088-2.81 2.81 9.186 9.105-9.095 9.184 2.81 2.81 9.112-9.192 9.18 9.1z"/></svg>
        Second
    </div>
</div>

<div class="popup__bg" data-popup="3">
    <div class="popup">
        <svg class="close-popup" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#2982ff" d="M23.954 21.03l-9.184-9.095 9.092-9.174-2.832-2.807-9.09 9.179-9.176-9.088-2.81 2.81 9.186 9.105-9.095 9.184 2.81 2.81 9.112-9.192 9.18 9.1z"/></svg>
        Third
    </div>
</div>

<style>
* {
    box-sizing: border-box;
}

body {
    margin: 0;
    padding: 0;
    font-family: 'Montserrat', sans-serif;
}

.wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-evenly;
    width: 100%;
    height: 100vh;
}

.open-popup {
    display: inline-block;
    padding: 15px 30px;
    text-transform: uppercase;
    background: #2982ff;
    color: #fff;
    text-decoration: none;
    font-weight: 500;
    border-radius: 5px;
}

.popup__bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background: rgba(0,0,0,0.5);
    opacity: 0;
    pointer-events: none;
    transition: 0.5s all;
}

.popup__bg.active {
    opacity: 1;
    pointer-events: all;
    transition: 0.5s all;
}

.popup {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    background: #fff;
    width: 400px;
    padding: 25px;
    transition: 0.5s all;
}

.popup__bg.active .popup {
    transform: translate(-50%, -50%) scale(1);
    transition: 0.5s all;
}

.close-popup {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
}

.popup label {
    width: 100%;
    margin-bottom: 25px;
    display: flex;
    flex-direction: column-reverse;
}

.popup .label__text {
    font-size: 14px;
    text-transform: uppercase;
    font-weight: 500;
    color: #cfd0d3;
    margin-bottom: 5px;
}

.popup input {
    height: 45px;
    font-size: 18px;
    border: none;
    outline: none;
    border-bottom: 1px solid #cfd0d3;
}

.popup input:focus {
    border-bottom: 1px solid #2982ff;
}

.popup input:focus + .label__text {
    color: #2982ff;
}

.popup textarea {
    resize: none;
    width: 100%;
    height: 150px;
    border: none;
    outline: none;
    border-bottom: 1px solid #cfd0d3;
    font-size: 18px;
    padding-top: 5px;
}

.popup textarea:focus {
    border-bottom: 1px solid #2982ff;
}

.popup textarea:focus + .label__text {
    color: #2982ff;
}

.popup button {
    width: 100%;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 18px;
    border: 2px solid #2982ff;
    background: #2982ff;
    cursor: pointer;
    text-transform: uppercase;
    transition: 0.5s all;
}

.popup button:hover {
    background: #fff;
    color:#2982ff;
    transition: 0.5s all;
}
</style>
<script>
window.addEventListener('click', e => {
  if (
    !e.target ||
    !e.target.closest('.close-popup') && 
    !e.target.matches('.popup__bg')
  ) {
    return;
  }
  
  e.target.closest('[data-popup]').classList.remove('active');
});

window.addEventListener('click', e => {
  if (!e.target.closest('[data-popup-id]')) {
    return;
  }
  
  const popupId = e.target.closest('[data-popup-id]').dataset.popupId;
  
  document.querySelectorAll(`[data-popup="${popupId}"]`).forEach(node => {
    node.classList.add('active');
  });
});
</script>


Попапы можно делать используя тег dialog.
Ответить с цитированием
  #3 (permalink)  
Старый 01.03.2024, 23:57
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

Nexus,
достаточно одной таблетки...
window.addEventListener('click', e => {
            if (
                e.target.closest('.close-popup, .popup__bg')
            ) e.target.closest('[data-popup]').classList.remove('active');

            if (e = e.target.closest('[data-popup-id]')) {
                const popupId = e.dataset.popupId;
                const node = document.querySelector(`[data-popup="${popupId}"]`);
                node?.classList.add('active');
            }
        });
Ответить с цитированием
  #4 (permalink)  
Старый 02.03.2024, 03:22
Профессор
Отправить личное сообщение для Nexus Посмотреть профиль Найти все сообщения от Nexus
 
Регистрация: 04.12.2012
Сообщений: 3,733

рони, да, можно все в один обработчик затолкать, но у меня их 2 для большей наглядности, один отвечает за открытие, второй за закрытие попапа.

С вашим кодом любой клик по контенту попапа приведет к его закрытию, т.к. `.popup_bg` - родительский контейнер для всего его содержимого, у меня не просто так вместо метода `closest` использовался `matches`.

window.addEventListener("click", e => {
  if (e.target.closest(".close-popup") || e.target.matches(".popup__bg")) {
    e.target.closest("[data-popup]").classList.remove("active");
  }

  const openPopupNode = e.target.closest("[data-popup-id]");
  if (openPopupNode) {
    const popupId = openPopupNode.dataset.popupId;
    
    document.querySelector(`[data-popup="${popupId}"]`)?.classList.add("active");
  }
});
Ответить с цитированием
  #5 (permalink)  
Старый 02.03.2024, 10:04
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,072

Сообщение от Nexus
использовался `matches`.
ок!
Ответить с цитированием
  #6 (permalink)  
Старый 06.03.2024, 15:51
Новичок на форуме
Отправить личное сообщение для Лена Лапина Посмотреть профиль Найти все сообщения от Лена Лапина
 
Регистрация: 19.02.2016
Сообщений: 9

Спасибо!
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Кросс-доменный запрос Ajax на чистом JS Setraiser AJAX и COMET 5 17.05.2019 18:54
Как сделать поле ввода тегов\меток на чистом js gunner17 Events/DOM/Window 2 21.03.2019 09:01
Проекты на чистом js kidar2 Общие вопросы Javascript 7 09.01.2014 14:26
Несколько модалных окон simplemodal Yan.Total jQuery 0 13.06.2013 20:14
Передать несколько значений из JS на сервер, методом POST балерун Общие вопросы Javascript 1 02.03.2010 14:36