Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda