Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Javascript addEventListener function triggering immediately

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda