'close popup by clicking outside of it in foreach functions
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 class="close-card-popup" id="close-card-popup">×</div>' +
'<p class="card-popup-text">Il prezzo di ' + getName.innerText + ' è di:</p>' +
'<p class="card-popup-price">' + getPrice.innerText + ' €' +
'<div class="card-popup-center"><button class="card-popup-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)
}))
Solution 1:[1]
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)
Solution 2:[2]
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 class="close-card-popup" id="close-card-popup">×</div>' +
'<p class="card-popup-text">Il prezzo di ' + getName.innerText + ' è di:</p>' +
'<p class="card-popup-price">' + getPrice.innerText + ' €' +
'<div class="card-popup-center"><button class="card-popup-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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user3945851 |
| Solution 2 | Frederic Brüning |
