Всем привет! В общем, такая ситуация, у меня есть попап, который вызывается при помощи атрибута data-modal
При нажатию на кнопку все работает замечательно. <button data-modal="1"></button>
Но у меня не получается тоже самое провернуть с тегом <a>.
Подскажите как решается эта проблема, а то гугл мне особо не помог(
!function(e){"function"!=typeof e.matches&&(e.matches=e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||function(e){for(var t=this,o=(t.document||t.ownerDocument).querySelectorAll(e),n=0;o[n]&&o[n]!==t;)++n;return Boolean(o[n])}),"function"!=typeof e.closest&&(e.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode}return null})}(window.Element.prototype);
document.addEventListener('DOMContentLoaded', function() {
/* Записываем в переменные массив элементов-кнопок и подложку.
Подложке зададим id, чтобы не влиять на другие элементы с классом overlay*/
var modalButtons = document.querySelectorAll('.js-open-modal'),
overlay = document.querySelector('.js-overlay-modal'),
closeButtons = document.querySelectorAll('.js-modal-close');
/* Перебираем массив кнопок */
modalButtons.forEach(function(item){
/* Назначаем каждой кнопке обработчик клика */
item.addEventListener('click', function(e) {
/* Предотвращаем стандартное действие элемента. Так как кнопку разные
люди могут сделать по-разному. Кто-то сделает ссылку, кто-то кнопку.
Нужно подстраховаться. */
e.preventDefault();
/* При каждом клике на кнопку мы будем забирать содержимое атрибута data-modal
и будем искать модальное окно с таким же атрибутом. */
var modalId = this.getAttribute('data-modal'),
modalElem = document.querySelector('.modal[data-modal="' + modalId + '"]');
/* После того как нашли нужное модальное окно, добавим классы
подложке и окну чтобы показать их. */
modalElem.classList.add('active');
overlay.classList.add('active');
}); // end click
}); // end foreach
closeButtons.forEach(function(item){
item.addEventListener('click', function(e) {
var parentModal = this.closest('.modal');
parentModal.classList.remove('active');
overlay.classList.remove('active');
});
}); // end foreach
document.body.addEventListener('keyup', function (e) {
var key = e.keyCode;
if (key == 27) {
document.querySelector('.modal.active').classList.remove('active');
document.querySelector('.overlay').classList.remove('active');
};
}, false);
overlay.addEventListener('click', function() {
document.querySelector('.modal.active').classList.remove('active');
this.classList.remove('active');
});
}); // end ready
/* modal */
.modal {
width: 420px;
background: white;
padding: 48px;
height: auto;
opacity: 0;
visibility: hidden;
max-width: 500px;
/* Центрируем и задаем z-index */
position: fixed;
top: 0%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 30; /* Должен быть выше чем у подложки*/
transition: .3s all;
}
.modal p{
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 24px;
margin-top: 16px;
}
.modal h2{
font-style: normal;
font-weight: bold;
font-size: 48px;
line-height: 40px;
}
.modal input {
margin-top: 16px;
width: 420px;
height: 48px;
background: #F7F4FB;
border-radius: 4px;
border: none;
padding-left: 12px;
box-sizing: border-box;
font-family: "MyWebFont";
font-style: normal;
font-weight: normal;
font-size: 16px;
line-height: 24px;
}
.modal select {
margin-top: 16px;
width: 420px;
height: 48px;
background: #F7F4FB;
border-radius: 4px;
border: none;
padding-left: 12px;
box-sizing: border-box;
color: #241A33;
opacity: 0.6;
}
.modal input::placeholder {
padding: 24px 12px;
color: #241A33;
opacity: 0.6;
}
#check {
width: 16px;
height: 16px;
margin-right: 16px;
}
.modal button {
margin-top: 16px;
width: 420px;
height: 48px;
background: #2560F7;
border-radius: 4px;
color: #F7F4FB;
}
.overlay {
/* Скрываем подложку */
opacity: 0;
visibility: hidden;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .5);
z-index: 20;
transition: .3s all;
}
/* Стили для активных классов подложки и окна */
.modal.active {
opacity: 1;
visibility: visible;
top: 50%;
}
.overlay.active{
opacity: 1;
visibility: visible;
}
/* Стили для кнопки закрытия */
.modal__cross {
cursor: pointer;
}
<p> <a href="/" data-modal="1">Привет</a></p>
<button class="sub js-open-modal" data-modal="1"></button>
<div class="modal" data-modal="1">
<div style="display: flex; flex-direction: row; justify-content: space-between;"><h2>Подписка</h2>
<img src="/img/svg/Vector (1).svg" alt="close" class="modal__cross js-modal-close"></div>
<p>кек</p>
<input type="text" placeholder="Имя">
<div style="display: flex; flex-direction: row;">
<input type="tel" placeholder="Телефон" style="margin-right: 20px;">
<input type="email" placeholder="Эл.почта" style="max-width: 191px;">
</div>
<select required placeholder="Страна" name="filesB" id="filesB" >
<option value="RU" data-class="ru">Россия</option>
<option value="UKR" data-class="ukr">Украина</option>
<option value="KZ" data-class="kz">Казахстан</option>
<option value="UZ" data-class="uz">Узбекистан</option>
<option value="KG" data-class="kg">Киргизия</option>
<option value="TG" data-class="tg">Таджикистан</option>
<option value="TR" data-class="tr">Туркменистан</option>
</select>
<input type="text" placeholder="Населенный пункт">
<div style="display: flex; flex-direction: row;">
<input type="checkbox" name="check" id="check">
<p style="width: 396px;height: 48px;margin-right: -45px;"> Согласен с политикой конфиденциальности и даю согласие на обработку персональных данных</p>
</div>
<button> Подписаться</button>
</div>
Ответы (1 шт):
Автор решения: humster_spb
→ Ссылка
Очевидно же, что дело не только в data-атрибуте, но и соответствующем классе js-open-modal. Для кнопки он прописан, а для ссылки - нет, потому и не работает.