Day 11/30 - Talk JavaScript To Me: Event Propagation
Prakash Pun
Senior Frontend Developer at Persistent Systems | ReactJS, Web Performance, Scalable UI Design | Crafting intuitive user experiences that drive results
Let's start with a silly programming joke, shall we ? ??
Why do programmers hate the outdoors?
Too many bugs.??
Today, I want to break down a fundamental concept in JavaScript that can sometimes be tricky for beginners: Event Propagation. This includes Capturing and Bubbling phases. Let's dive in! ??
What is Event Propagation?
Event propagation is how events travel through the DOM (Document Object Model) tree in web development. When you interact with an element on a webpage, like clicking a button, that interaction (event) can be handled by multiple elements in the DOM. Understanding how this works can help you better manage these events.
The Capturing Phase
Imagine you have a series of nested elements: div > ul > li. When an event is triggered, the browser checks if any of the parent elements have a handler for the event.
For example:
<div id="div1">
<ul id="ul1">
<li id="li1">Click me!</li>
</ul>
</div>
If you click on the li element, the event first travels down from the div, to the ul, and finally to the li. This phase is known as capturing.
To add an event listener in the capturing phase, you can do:
document.getElementById("div1").addEventListener("click", () => {
console.log("DIV captured");
}, true); // The third parameter `true` sets the listener for capturing
The Bubbling Phase
After the event reaches the target element (li), it starts bubbling back up to the root. This means the event will travel from li, up to ul, and finally to div.
Using the same structure:
领英推荐
document.getElementById("div1").addEventListener("click", () => {
console.log("DIV bubbled");
}, false); // The third parameter `false` sets the listener for bubbling
Putting it all together:
When you click on the li element, you'll see logs for both capturing and bubbling:
document.getElementById("div1").addEventListener("click", () => {
console.log("DIV captured");
}, true);
document.getElementById("ul1").addEventListener("click", () => {
console.log("UL captured");
}, true);
document.getElementById("li1").addEventListener("click", () => {
console.log("LI clicked");
});
document.getElementById("ul1").addEventListener("click", () => {
console.log("UL bubbled");
}, false);
document.getElementById("div1").addEventListener("click", () => {
console.log("DIV bubbled");
}, false);
Why is this important?
Understanding capturing and bubbling is crucial for:
Quick Tips:
Mastering event propagation can make your code more robust and easier to manage. Happy coding! ??
Feel free to reach out if you have any questions or want to discuss more about JavaScript and its quirks! Even if you do not agree with this post ??
#JavaScript #Coding #WebDevelopment #Learning #BeginnerTips #Programming