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

192
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

add

event.stopPropagation()

to your clk function

about 4 years ago · Santiago Trujillo Denunciar

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 Denunciar
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