Home > front end >  close popup by clicking outside of it in foreach functions
close popup by clicking outside of it in foreach functions

Time:03-16

i've created a sample project with a card slider, inside this slider i've created a foreach functions that open a popup when the card is clicked, with some information.

the problem is that i can't find a way to close popup if i click outside of the popup elements.

here a reproducible example: https://jsfiddle.net/7hg4y9ro/

my function:

const cards = document.querySelectorAll('.cards')

cards.forEach((card => {

    const getName = card.querySelector('.footer-left')
    const getPrice = card.querySelector('.footer-right')

    function showPopup() {
        const el = document.getElementById('cards-container');
        const popup = document.createElement('div')
        popup.setAttribute('class', 'card-popup')

        popup.innerHTML = ''  
            '<div  id="close-card-popup">&times;</div>'  
            '<p >Il prezzo di '   getName.innerText   ' è di:</p>'  
            '<p >'   getPrice.innerText   ' €'  
            '<div ><button >Acquista il prodotto</button></div>'

        const overlay = document.createElement('div')
        overlay.setAttribute('class', 'overlay')
        el.appendChild(overlay)
        el.appendChild(popup)

    }

    card.addEventListener('click', showPopup)

}))

CodePudding user response:

Since you are creating elements, you could delete them. Like this:

function hidePopup() {
    document.querySelector('.card-popup').remove()
    document.querySelector('.overlay').remove()
}

function showPopup() {
    const el = document.getElementById('cards-container');
    const popup = document.createElement('div')
    popup.setAttribute('class', 'card-popup')

    popup.innerHTML = ''  
        '<div  id="close-card-popup">&times;</div>'  
        '<p >Il prezzo di '   getName.innerText   ' è di:</p>'  
        '<p >'   getPrice.innerText   ' €'  
        '<div ><button >Acquista il prodotto</button></div>'

    const overlay = document.createElement('div')
    overlay.setAttribute('class', 'overlay')
    el.appendChild(overlay)
    el.appendChild(popup)
    
    document.querySelector('.close-card-popup').addEventListener('click', hidePopup)
    document.querySelector('.overlay').addEventListener('click', hidePopup)
}

But I'd do it with CSS instead of JS using the :target pseudo class.

CodePudding user response:

Just add at the end of your showPopup() function this code:

    function closePopup(){
        popup.remove()
        overlay.remove()
    }
    overlay.addEventListener('click', closePopup)
    var elem = document.querySelector('.close-card-popup')
    elem.addEventListener('click', closePopup)
  • Related