@LI4NOOST

Как закрыть Popup при клике на пустое место?

HTML
<!DOCTYPE html>
<html lang="ru">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./pages/index.css">
    <title>Место</title>
</head>

<body class="page">
    <div class="wrapper">
        <header class="header">
            <img class="header__logo" src="./images/vector/header__logo.svg" alt="Лого">
        </header>
        <section class="profile">
            <img class="profile__avatar" src="./images/jpg/kysto.jpg" alt="Кусто">
            <article class="profile__info">
                <div class="profile__heading">
                    <h1 class="profile__name">Жак-Ив Кусто</h1>
                    <button type="button" class="profile__edit-button"></button>
                </div>
                <p class="profile__subtitle">Исследователь океана</p>
            </article>
            <button type="button" class="profile__add-button"></button>
        </section>
        <section class="elements">


        </section>
        <footer class="footer">
            <h2 class="footer__copyright">© 2020 Mesto Russia</h2>
        </footer>
    </div>
    <div class="popup">
        <div class="menu">
            <button class="menu__close-icon" type="button"></button>
            <h2 class="menu__title">Редактировать профиль</h2>
            <form class="form" novalidate name="formProfile" >
                <input id = "user-name" type="text" name="menuName" required minlength="2" maxlength="40" placeholder="Имя" class="form__input form__input_type_name">
                <span id= "user-name-error" class="error-span"></span>
                <input id = "about" type="text" name="menuSubtitle" required minlength="2" maxlength="200" placeholder="Вид деятельности"
                    class="form__input form__input_type_job">
                    <span id= "about-error" class="error-span"></span>
                <button disabled type="submit" class="menu__button menu__submit">
                    Сохранить
                </button>
            </form>
        </div>
    </div>
    <div class="popup popup_type_cards">
        <div class="menu-cards menu">
            <button class="menu__close-icon menu__card-close" type="button"></button>
            <h2 class="menu__title menu__title-cards">Новое место</h2>
            <form class=" form form-cards" name="formCards"  novalidate>
                <input id = "cardName" type="text" name="nameCard" placeholder="Название" minlength="2" maxlength="30" required novalidate class="form__input form-cards__input form-cards__input_type_text">
                <span id= "cardName-error" class="error-span"></span>
                <input id = "link" type="url" name="linkCard" required novalidate minlength="2" placeholder="Ссылка на картинку"
                    class="form__input form-cards__input form-cards__input_type_link">
                    <span id= "link-error" class="error-span"></span>
                <button disabled type="submit" class="menu__button menu-cards__buttonCreate menu__submit" value="Создать">
                    Создать
                </button>
            </form>
        </div>
    </div>
    <template class="card-template">
        <div class="card">
            <button class="card__button-delete" type="button"></button>
            <img src="none" alt="none" class="card__image">
            <div class="card__description">
                <h2 class="card__title"></h2>
                <button class="card__button-like" type="button"></button>
            </div>
        </div>
    </template>

    <div class="popup popup_type_image">
        <div class="image-container">
            <h2 class="image-container__title"></h2>
            <img class="image-container__open-image" src="none" alt="none">
            <button class="image-container__close-icon" type="button"></button>
        </div>
    </div>
    <script src="./scripts/const.js"></script>
    <script src="./scripts/script.js"></script>
    <script src="./scripts/validate.js"></script>

</body>

</html>

JS
//Перебор массива
initialCards.forEach(function (value) {
    const item = renderItem(value.name, value.link);
    container.prepend(item);
});

// функция рендеренга
function renderItem(text, link) {
    const newCard = cardTemplate.cloneNode(true) //Клоним кароточку
    const cardTitle = newCard.querySelector('.card__title')
    const cardImage = newCard.querySelector('.card__image')
    cardImage.src = link
    cardImage.alt = text
    cardTitle.textContent = text;
    //Добавить обработчик
    setListenersForButtons(newCard);
    //Возвращаем карточку
    return newCard;

}
//Добавление карточки 
function handleSubmit(evt) {
    evt.preventDefault()
    const item = renderItem(mestoName.value, mestoLink.value);
    container.prepend(item);

}
// Создать обработчики для кнопок
function setListenersForButtons(element) {
    const cardDeleteButton = element.querySelector('.card__button-delete');
    cardDeleteButton.addEventListener('click', handleDelete);
    const cardLikeButton = element.querySelector('.card__button-like');
    cardLikeButton.addEventListener('click', handleLike);
    const cardScreen = element.querySelector('.card__image');
    cardScreen.addEventListener('click', handleOpenCardImagePreview);
}


//Удаление карточки
function handleDelete(event) {
    const currentCard = event.target.closest('.card');
    currentCard.remove()
};
// кнопка лайка 
function handleLike(event) {
    const currentLike = event.target.closest('.card__button-like')
    currentLike.classList.toggle('card__button-like_active')
};

// Добавление модального окна
function handleOpenCardImagePreview(cardData) {
    popupImageOpenTitle.textContent = cardData.currentTarget.alt;
    popupImages.alt = cardData.currentTarget.alt;
    popupImages.src = cardData.currentTarget.currentSrc;
    openPopup(popupImg);
}

const closeImagePopupButton = document.querySelector('.image-container__close-icon')
closeImagePopupButton.addEventListener('click', () => {
    closePopup(popupImg)
});

//Открытие popup
function openPopup(popupElem) {
    popupElem.classList.remove('animation-close')
    addClickListner ()
    popupElem.classList.add('popup_active');
    textName.value = profileNameText.textContent 
    textSubtitle.value = profileSubtitleText.textContent
};
//Закрытие popup
function closePopup(popupElem) {
    setTimeout(() => popupElem.classList.remove('popup_active'), 500);
    popupElem.classList.add('animation-close');
};


document.addEventListener('keydown', (e) => {
    if (e.keyCode === esc) {
        console.log(cerrentPopup);
    }
});

function addClickListner () {
document.addEventListener('click', (e) => {
    const click = e.composedPath().includes(menu)|| e.composedPath().includes(buttonEditProfile) 
    || e.composedPath().includes(buttonAdd) || e.composedPath().includes(formCardsElement) 
    || e.composedPath().includes(menuTitle) || e.composedPath().includes(menuCardTitle) || e.composedPath().includes(popupImages)
    if (!click) {
        closePopup(popupEditProfile)
        closePopup(popupCards)
    }
    console.log(click);
})
}

// Форма добавления картинки
buttonAdd.addEventListener('click', () => {
    const form = popupCards.querySelector('.form');
    form.reset();
    openPopup(popupCards);
});
addPopupEventHandlers(popupCards, (evt) => {
    evt.preventDefault()
    const item = renderItem(mestoName.value, mestoLink.value);
    container.prepend(item);
});

// Форма редактирования профиля
buttonEditProfile.addEventListener('click', () => {
    openPopup(popupEditProfile);
});
addPopupEventHandlers(popupEditProfile, (evt) => {
    evt.preventDefault();
    profileNameText.textContent = textName.value;
    profileSubtitleText.textContent = textSubtitle.value;
});

function addPopupEventHandlers(popupElement, submitHandler) {
    const closeButton = popupElement.querySelector('.menu__close-icon');
    const form = popupElement.querySelector('.form');

    form.addEventListener('submit', evt => {
        submitHandler(evt);
        closePopup(popupElement);
    });

    closeButton.addEventListener('click', () => {
        closePopup(popupElement);
    });
}

Надо закрывать POPup по клику вне его. Удалось реализовать это, но очень косячно, в функции addClickListiner. Даны 3 разных popup (popupEditProfile, popup-cards, popup-img). И чтобы закрывать их используется функция closePopup (). Нужно сделать функцию closepopup и addClickListiner универсальными. Чтобы функция могла отследить, какой popUp открыт и закрывать его, при ее вызове. А addClickListiner реализовать так, чтобы задать правила клика по пустому месту тоже для открытого POPup.
  • Вопрос задан
  • 298 просмотров
Пригласить эксперта
Ответы на вопрос 1
Ваш ответ на вопрос

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

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