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

196
Visualizações
Click handler being invoked twice on same element

I have two div elements, inner and outer. I am triggering click event on inner div programmatically only once. But the log shows that the event handler is invoked twice on inner div. Here is the code. Can you please help understand why is this happening. Code is also hosted on codesandbox

const inner = document.querySelector(".inner");
const outer = document.querySelector(".outer");
    
function clk(event) {
  console.log("click");
  console.log(event.target);
}
    
inner.addEventListener("click", clk);
outer.addEventListener("click", clk);
    
inner.click();
<div class="outer" id="div1">
  <div class="inner" id="div2"></div>
</div>

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This is because of Event bubbling.

What's happening is :

  1. You tigger the click event on inner.
  2. The event listener of inner is called.
  3. The click event bubbles up to outer.
  4. The event listener of outer is called

The target is inner in both calls to the clk function, because it's a property of the initial event. It doesn't depend on the element the listener is registered on.

about 4 years ago · Santiago Trujillo Relatório

0

add

event.stopPropagation()

to your clk function

about 4 years ago · Santiago Trujillo Relatório

0

The event is only triggered once per element. You can see this if you use the currentTarget rather than the target

function clk(event) {
  console.log("click");
  console.log(event.currentTarget);
}
about 4 years ago · Santiago Trujillo 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