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


Solution 1:[1]

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.

Solution 2:[2]

It happens because you subscribe on outer as well as on inner because of event bubbling effect which is presented in JavaScript(see: https://javascript.info/bubbling-and-capturing). That`s why it is executed on inner and outer element - you added handler for both:

inner.addEventListener("click", clk);
outer.addEventListener("click", clk);

Solution 3:[3]

add

event.stopPropagation()

to your clk function

Solution 4:[4]

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);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Araelath
Solution 2 Mykyta Halchenko
Solution 3 DCR
Solution 4 Blake Plumb