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

204
Views
How to add click event listener only after click event listener has been triggered?

I am trying to achieve the following functionality: Once user has clicked on a button, I want to add click event listener to window element to alert a message (say).

Consider the below snippet for this purpose:

<button id="b1">click</button>

  <script>
    document.querySelector("#b1").addEventListener('click', () => {
      window.addEventListener("click", () => {
        alert("hello");
      });
    })
  </script>

But, unfortunately, the above code also alerts message when the user initially clicks on button (which I don't want). Any idea on how I can achieve the functionality?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It would be better to add the window click event listener and have a flag to determine if the alert should appear.

The problem with the method you are using is every time a user clicks the button you add a new event listener to the window. This will then stack up and fire multiple times for each click of the document.

To stop the button click from passing through to the document and also triggering the window event listener you can use the event stopPropagation() method as demonstrated below.

let hasButtonBeenClicked = false;

window.addEventListener("click", () => { 
  if(hasButtonBeenClicked) {
    alert("hello");
    hasButtonBeenClicked = false;
  }
});
document.querySelector("#b1").addEventListener('click', (e) => {
  e.stopPropagation()
  hasButtonBeenClicked = true;
})
<button id="b1">click</button>

about 4 years ago · Juan Pablo Isaza Report
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!