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

198
Views
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 answers
Answer question

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 Report

0

add

event.stopPropagation()

to your clk function

about 4 years ago · Santiago Trujillo Report

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