I know that this question has been asked before, so I'm sorry for the duplicate but none of the answers I have seen have worked for me.
In my page I have some elements that look like this (with distinct ids):
<div id="AGTcard" class="popup">
<button type="button" class="close_button" onclick="ClosePopup('AGTcard')">X</button>
<div class="info_div scroll">
<p>Anderson (Oak Ridge)-AGT (TN)</p>
</div>
</div>
There is a button on the page that triggers a javascript function to make this element appear on the page. The function is supposed to add an event listener to the document to check if the user clicks outside of the element, and if they do then the element should be hidden again. This is my javascript code:
function CloseClick(e){
var popups = document.getElementsByClassName('popup')
var current_poppup;
for (var i=0;i<popups.length;i++){
if (popups[i].style.display == 'block'){
current_poppup = popups[i]
}
}
if (!current_poppup.contains(e.target)){
ClosePopup(current_poppup.id)
}
}
function InfoPopup(in_id){
var popup = document.getElementById(in_id)
popup.style.display='block'
document.addEventListener('click',CloseClick)
console.log('added event listener')
}
function ClosePopup(in_id){
var popup = document.getElementById(in_id)
popup.style.display='none'
document.removeEventListener('click',CloseClick)
console.log('removed event listener')
}
The InfoPopup(in_id) function is triggered on click of a button.
Whenever I click on the button to make the element visible, the addEventListener function triggers on the same click and immediately hides the element again. I can't figure out a way to stop this from happening.