Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click handler being invoked twice on same element [duplicate]

Tags:

javascript

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>
like image 315
A Singh Avatar asked Sep 16 '25 22:09

A Singh


1 Answers

add

event.stopPropagation()

to your clk function

like image 164
DCR Avatar answered Sep 18 '25 18:09

DCR