From 7749d1cdd27cb7258f9f3239b29a6e0400f3247b Mon Sep 17 00:00:00 2001 From: Amrit Singhal Date: Thu, 17 Oct 2024 23:54:34 +0530 Subject: [PATCH] Update README.md --- README.md | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e67635b5..920f84aa 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ All the translations for this repo will be listed below: 31. **[Design Patterns](#31-design-patterns)** 32. **[Partial Applications, Currying, Compose and Pipe](#32-partial-applications-currying-compose-and-pipe)** 33. **[Clean Code](#33-clean-code)** - +34. **[Additonal Concepts](additional-concept)** --- ## 1. Call Stack @@ -1282,7 +1282,43 @@ The Event Loop is a critical part of JavaScript’s concurrency model, ensuring - 🎥 [JavaScript Clean Code](https://youtu.be/vPXzVNmCPg4?si=QR1k4E6Zx5H4mfcs) - 🎥 [Tips On Learning How To Code](https://www.youtube.com/watch?v=0wHyoBPc6zs) +## Additional Concept + # Event Bubbling in JavaScript + +Event bubbling is a fundamental concept in JavaScript that refers to how events propagate up through the DOM (Document Object Model). When an event, such as a `click`, occurs on an element, it doesn't just stop there—it "bubbles" up to its parent elements and continues to propagate all the way up to the root element (`document`). + +This propagation follows the event flow, starting from the innermost target element (where the event is triggered) and moving outward through the ancestors, following the DOM hierarchy. By default, JavaScript uses the event bubbling model, but it also allows developers to control and manipulate this behavior. + +## Example of Event Bubbling + +Consider a scenario where you have a button inside a `div`. When you click the button, the event propagates and is also captured by the `div` unless event bubbling is stopped explicitly. + + ### +
+ +
+ + **[⬆ Back to Top](#table-of-contents)** ## License +// JavaScript to handle the click event +document.getElementById("parent").addEventListener("click", function () { + console.log("Parent div clicked!"); +}); + +document.getElementById("child").addEventListener("click", function (event) { + console.log("Button clicked!"); + // Uncomment the following line to stop event bubbling + // event.stopPropagation(); +}); +element.addEventListener('click', eventHandler, true); // Capturing phase +element.addEventListener('click', eventHandler, false); // Bubbling phase (default) +document.getElementById("parent").addEventListener("click", function (event) { + if (event.target.tagName === "BUTTON") { + console.log("Button inside parent div clicked!"); + } +}); + + This software is licensed under MIT License, See [License](https://github.com/leonardomso/33-js-concepts/blob/master/LICENSE) for more information ©Leonardo Maldonado.