I want to define an EventListener
after clicking on a button
.
I set EventListener
in another EventListener
and want the child EventListener
to be listening to click event
only after the parent event was triggered.
Code snippet:
const btn = document.querySelector(".btn")
btn.onclick = function() {
console.log("PARENT")
document.onclick = function() {
console.log("CHILD")
}
}
<button class="btn">Click</button>
Current behavior:
Parent and child events
trigger together, even on the first click on the button.
So, even on the first click on the button
I see "PARENT" "CHILD"
in console, but I want to see only "PARENT"
.
Desired behavior:
Child EventListener
should be listening to click event
only after clicking on the button
element. Thus, I want to see on the first click on the button
only "PARENT"
in console and after on subsequent clicks: "PARENT" "CHILD"
.
Why it works in such way?
Why does the event
, defined in child EventListener
, trigger with the event
, defined in parent EventListener
, though child EventListener
should only start listening to click event
when the parent event
is triggered?