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>
This is because of Event bubbling.
What's happening is :
click event on inner.inner is called.click event bubbles up to outer.outer is calledThe 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.
add
event.stopPropagation()
to your clk function
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);
}