0

i have this delete-popup div

        <div class="delete-popup">
            <div class="popup-icon-box">
                <img src="icon/delete-icon.svg" alt="delete-icon" class="popup-icon" />
            </div>
            <h4 class="heading">Kamu yakin ingin menghapus?</h4>
            <p class="popup-text">Setiap buku yang telah dihapus tidak dapat dikembalikan lagi</p>
            <div class="popup-confirmation-button">
                <button class="btn btn--outline no-opacity">Cancel</button>
                <button class="btn btn--red">Delete</button>
            </div>
        </div>

and this is the event delegation i attach to the document

document.addEventListener("click", function (e) {
        if (isPopupShowed) {
            if (!e.target.classList.contains("delete-popup")) {
                deletePopup.classList.remove("show-popup");
                deletePopup.classList.add("close-popup");
                isPopupShowed = false;

                deletePopup.addEventListener("animationend", function () {
                    deletePopup.classList.remove("close-popup");
                });
            }
        }

        if (e.target.classList.contains("delete")) {
            deletePopup.classList.add("show-popup");
            isPopupShowed = true;
        }
    });

inside if(isPopupShowed) i check if user click outside the popup container then the popup will close however if i click element inside the container itself(e.g heading/icon/etc) it will also close the popup container. How do i prevent this from happening? i tried to use stopPropagation but it doesn't seem to work.

Foxter
  • 1
  • 1
  • why are you listening to the `document` event? use something like `document.querySelector('.delete-popup').addEventListener(...)` no? – Alberto Sinigaglia Jul 22 '21 at 10:09
  • You can check if the `event.target` is an ancestor of the popup container and stop if so. see: [Check if clicked element is descendant of parent, otherwise remove parent element](https://stackoverflow.com/questions/34621987/check-if-clicked-element-is-descendant-of-parent-otherwise-remove-parent-elemen) – pilchard Jul 22 '21 at 10:09
  • because the delete button that will trigger the popup is generated after adding data so i must use delegated function to check if the target contains("delete") @AlbertoSinigaglia – Foxter Jul 22 '21 at 10:28
  • @Foxter add the event listener after you create that element – Alberto Sinigaglia Jul 22 '21 at 10:30
  • 1
    Thank god it worked, thank you very much for the link you given, have a nice day @pilchard – Foxter Jul 22 '21 at 10:30
  • @AlbertoSinigaglia then i can't check if user click outside of the popup div, i'd still need to create document listener function to check where the user clicked – Foxter Jul 22 '21 at 10:31

0 Answers0