Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!