Propagation:
By propagation, we can understand how the events will travel through the DOM. From root to target (event capture) or from target to root (bubbling).
Propagation has two phases:
- Bubbling (from bottom element to top element)
- Event capture (from top element to bottom element)
Bubbling:
By default, in JavaScript, a bubbling effect occurs if we don’t change the captured property from false to true.
<body class="bod"><div class="one"><div class="two"><div class="three"></div></div></div>const divs = document.querySelectorAll("div");// Bubbling: When we set multiple nested elements, and integrate an eventListener with the elements, then we trigger eventListener on any of the elements. The event Listener effect will be bubbling from child to parent element.function showTextEffect() {console.log(this.classList.value);// Result:// three// two// one// bod}document.body.addEventListener("click", showTextEffect);divs.forEach((div) => div.addEventListener("click", showTextEffect));</body>
Event-capture:
<body class="bod"> <div class="one"> <div class="two"> <div class="three"></div> </div> </div> <script> const divs = document.querySelectorAll("div"); // Event capture: When we set multiple nested elements, and integrate an eventListener with the elements, then we trigger eventListener on any of the element. The event Listener effect will be bubbling from parent to child element. function showTextEffect() { console.log(this.classList.value); // Result: // one // two // three } // document.body.addEventListener("click", showTextEffect); divs.forEach((div) => div.addEventListener("click", showTextEffect, { capture: true, // by default, capture property will remain false, but if we set it to true, then the event of eventListener will be triggered from parent to child. once: true, // once property indicates that the eventListener will trigger for once. }), ); </script> </body>
Post a Comment