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

206
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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