'In Event Propogation, how does the event know when to fire?
In the following code:
<div onClick={() => console.log('outer div')}>
<div onClick={() => console.log('middle div')}>
<div onClick={() => console.log('innermost div')}>
Click me!
</div>
</div>
</div>
I understand that the event object possesses a target
property that contains a reference to the DOM node on which the event occurred. My question is: in the capturing (when capture set to true) and bubbling phases, will the event always fire on an HTML element if that element contains the same HTML attribute (ex. onClick, onHover) that started the propogation cycle? Thanks.
Solution 1:[1]
YES.
The event always fires on an HTML element if that element contains the same HTML attribute.
In the code below, you can see which phase of the event fires on a specific node.
Event.eventPhase
interface indicates which phase of the event flow is currently being evaluated.
0: none, 1: capturing, 2: target, 3: bubbling
// true: capturing / false: bubbling
const useCature = true;
const phase = (e) => {
const phases = ["capturing", "target", "bubbling"];
const node = `${e.currentTarget.nodeName} .${e.currentTarget.className}`;
console.log(node, phases[e.eventPhase - 1]);
};
document.querySelector(".outer").addEventListener("click", phase, useCature);
document.querySelector(".middle").addEventListener("click", phase, useCature);
document.querySelector(".inner").addEventListener("click", phase, useCature);
<div class="outer">
<div class="middle">
<div class="inner">
Click me!
</div>
</div>
</div>
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 |