🎯 Mastering DOM Events: Bubbling, Capturing & Delegation (JavaScript Essentials) When working with the DOM, understanding how events travel is crucial for writing clean, efficient, and maintainable code. Three key concepts help with that: 🔄 1. Event Bubbling When an event occurs on an element, it first triggers the handler on that element, and then moves up the DOM tree (parent → ancestor). Order: child → parent → document element.addEventListener("click", handler); // default: bubbling 📥 2. Event Capturing (Trickling) The opposite of bubbling. The event starts from the top (document) and travels down to the target element. Order: document → parent → child element.addEventListener("click", handler, true); // third parameter = capturing phase 🤝 3. Event Delegation (Real-World Best Practice) Instead of attaching event listeners to multiple child elements, we attach one listener to a parent and use event bubbling to detect which child triggered the event. This reduces: ✅ Memory usage ✅ DOM reflows ✅ Code duplication document.querySelector("ul").addEventListener("click", (e) => { if (e.target.tagName === "LI") { console.log("List item clicked:", e.target.innerText); } }); 🧠 Why This Matters Enhances performance Keeps code scalable (especially when elements are dynamically added/removed) Makes your event logic clean and maintainable 🌟 In Short: ConceptDirectionUse CaseCapturingDocument → ElementNiche control of early event flowBubblingElement → DocumentDefault & most commonly usedDelegationUses BubblingEfficient event handling for lists, tables, dynamic UI Understanding these three concepts is a core skill that reflects strong JavaScript & frontend fundamentals — a must for building dynamic, high-performance UI. #JavaScript #WebDevelopment #Frontend #ReactJS #DOM #CodingTips #DeveloperKnowledge #PerformanceEngineering
Mastering DOM Events: Bubbling, Capturing, Delegation for Efficient Code
More Relevant Posts
-
🎯 A Little Story About JavaScript Events While working on a UI feature recently, I was thinking about how neatly JavaScript handles user interactions — especially through event flow. Imagine this 👇 You click a button inside a card component. The click first triggers on the button... but somehow, the parent card also reacts. That’s not magic — that’s Event Bubbling in action. In bubbling, the event starts at the target element and travels up through all its ancestors until it reaches the top of the DOM. There’s also the opposite path — Event Capturing — where the event moves down from the root to the target. You can enable this phase using: element.addEventListener("click", handler, true); And sometimes, you just want that click to stay right where it happened — no parents involved. That’s when event.stopPropagation() steps in to save the day ✋ Understanding how events travel through the DOM makes handling complex interfaces so much smoother. It’s one of those core concepts that quietly powers every interactive web experience we build. #JavaScript #Frontend #WebDevelopment #Coding #TIL
To view or add a comment, sign in
-
🚀From Logic to Life: My First Interactive DOM Projects in JavaScript! Hello everyone 👋 Week 4 of my JavaScript journey marks a major shift — I’ve officially moved out of the console and into the browser with my first two fully interactive projects! 🎉 Mastering the DOM (Document Object Model) and Event Listeners helped me bridge the gap between pure JS logic and real-time user interaction. Seeing these projects come alive confirmed my understanding of functions, strings, and flow control in action. 💡Project Showcase: Putting Theory into Practice 🎨Project 1: The Color Switcher Goal: Dynamically change the background color of the entire page — either randomly or based on user input. Core Concepts Applied: DOM Manipulation: Reading input values (.value), updating element content (.textContent), and changing styles (.style.backgroundColor). Functions & Math: Generating random RGB values using Math.floor() and reusable functions. Conditional Logic: Checking if input is empty and using alert() for user feedback. 🧮Project 2: Simple Calculator Goal: Build a clean, interactive calculator that performs basic arithmetic operations. Core Concepts Applied: Event Handling: Using onclick directly in HTML (for simplicity) to trigger JS functions that append values. Error Handling: Using try...catch to prevent crashes from invalid inputs (like dividing by zero or invalid syntax). String Evaluation: Leveraging JavaScript’s eval() to safely calculate user-inputted expressions. 🧠Week 4 Takeaway: Confidence in Interaction The biggest lesson wasn’t just syntax — it was about managing state, handling user unpredictability, and writing defensive code. The calculator especially pushed me to think more like a developer, anticipating what could go wrong and planning for it. 💬Your Turn: What was the most challenging feature for you when you built your first calculator or interactive project? I’d love to hear your experience! 👇 #JavaScript #DOMManipulation #MiniProjects #FrontendDevelopment #CodingJourney #WebDevelopment #LearnInPublic #FrontendLearning #BuildInPublic
To view or add a comment, sign in
-
☕ Revisiting JavaScript Event Flow — Capturing, Target & Bubbling Phases Today, I was revising one of the most important concepts in JavaScript — Events and Event Listeners. 💡 It’s fascinating how a single click can travel through multiple layers of the DOM before reaching its destination! Here’s what I learned and revised 👇 🔹 Event & Event Listener JavaScript allows us to respond to user interactions like clicks, key presses, and mouse movements. For example 👇 element.addEventListener("click", () => { console.log("Element clicked!"); }); This method lets us attach multiple handlers to the same element without overwriting existing ones. 🔹 Click Event The click event is one of the most commonly used — and it’s the one I focused on today while understanding how event flow actually works. 🔹 Event Flow in JavaScript Every event in the DOM passes through three phases: 1️⃣ Capturing Phase – The event travels from the top (document) down to the target element. 2️⃣ Target Phase – The exact element that triggered the event receives it. 3️⃣ Bubbling Phase – The event then bubbles back up toward the document. 📘 Example // Capturing phase parent.addEventListener("click", () => { console.log("Parent clicked - Capturing Phase"); }, true); // true → capturing // Bubbling phase (default) child.addEventListener("click", () => { console.log("Child clicked - Bubbling Phase"); }); 👉 When you pass true as the third argument in addEventListener, it listens during the capturing phase. 👉 By default, it’s false, meaning the listener works in the bubbling phase. 🧠 Visual Flow 📤 Document → HTML → Body → Parent → Child → (then bubbles back up 🔁) Understanding this complete flow helped me clearly visualize how events travel and how to control them precisely using capturing and bubbling. 🚀 A huge thanks to CoderArmy, Rohit Negi, and Aditya Tandon Sir 🙏 Your clear explanations and practical examples made this topic so easy to grasp. #JavaScript #EventListener #EventFlow #FrontendDevelopment #WebDevelopment #LearningJourney #Coding #Developer #RohitNegi #AdityaTandon #CoderArmy
To view or add a comment, sign in
-
GitHub : https://lnkd.in/gvjUhzmC 🔥 Day 1 of 20 JavaScript Micro-Projects 👨💻 Today we’re building a fully responsive navbar using only HTML, CSS & Vanilla JS — no frameworks, no shortcuts, just raw frontend grind. Modern UI, glass effect, smooth animations, mobile hamburger toggle — this is how real devs learn UI fundamentals. Because before React, before frameworks, before hype… there were skills. We build foundations. We sharpen fundamentals. We rise. 💡 Project #1: Responsive Navbar 🧠 Concepts: DOM manipulation, class toggling, mobile-first layout 🔗 GitHub repo in bio ⚡ Follow for 19 more fire projects Let’s craft greatness — one line of code at a time. 🚀💙 #javascript #frontend #webdevelopment #htmlcssjavascript #javascriptprojects #frontendprojects #vanillajs #webdev #cssdesign #responsivewebdesign #coderlife #uiuxdesign #codingreels #learnjavascript #frontenddeveloper #programminglife #javascriptreels #100daysofcode #webdevcommunity #codetutorial #buildinpublic #softwareengineering #techcontent #devcommunity #codeweaver
To view or add a comment, sign in
-
🚀 Web Dev Day 32: Mastering JavaScript Events — Making the Web Come Alive! ✨ Today’s session was all about DOM Events — the real magic behind user interaction in web development. Every click, scroll, or keypress you make triggers an event — and learning how to handle them properly separates a coder from a developer. 💡 🔹 Part 1: The Fundamentals of Events What is a DOM Event? Think of it like a doorbell — when a user interacts, JavaScript gets notified. 🔔 The 3 Core Components: Target: The element that triggers the event. Event Type: The kind of interaction (e.g., click, input, mouseover). Handler: The function that runs when the event occurs. Modern Approach: Use addEventListener() — it’s flexible, cleaner, and supports multiple listeners. Why Avoid onclick: It mixes HTML and JS, breaking Separation of Concerns. The Event Object: A built-in “information packet” containing details like mouse position, key pressed, and more. 🔹 Part 2: The Three Phases of an Event Event Bubbling: Events rise from the deepest element (child) up to its ancestors (parent → document). Event Capturing: The reverse — events travel from the top (document) down to the target. Visualizing Flow: Understanding how the browser processes events step by step helps debug like a pro. Control the Flow: Use event.stopPropagation() to prevent events from bubbling further when needed. 🧠 🔹 Part 3: The Event Delegation Pattern What Is It? Instead of adding listeners to multiple elements, attach one listener to a parent element. Why It’s Powerful: Better performance and easier management, especially for dynamic content. Key Tools: event.target → The actual element clicked. event.currentTarget → The element the listener is attached to. Real-World Example: Building an interactive to-do list where all items respond to clicks — with just one event listener! ✅ 🎯 Takeaway: Events are the heartbeat of interactive web apps. Understanding how they flow, bubble, and delegate gives you total control over your UI. #Day32 #JavaScript #WebDevelopment #Frontend #DOMEvents #EventHandling #CodingJourney #LearnInPublic #JS #Programming #CoderArmy #RohitNegi
To view or add a comment, sign in
-
-
🚀 Web Dev Day 32: Mastering JavaScript Events — Making the Web Come Alive! ✨ Today’s session was all about DOM Events — the real magic behind user interaction in web development. Every click, scroll, or keypress you make triggers an event — and learning how to handle them properly separates a coder from a developer. 💡 🔹 Part 1: The Fundamentals of Events What is a DOM Event? Think of it like a doorbell — when a user interacts, JavaScript gets notified. 🔔 The 3 Core Components: Target: The element that triggers the event. Event Type: The kind of interaction (e.g., click, input, mouseover). Handler: The function that runs when the event occurs. Modern Approach: Use addEventListener() — it’s flexible, cleaner, and supports multiple listeners. Why Avoid onclick: It mixes HTML and JS, breaking Separation of Concerns. The Event Object: A built-in “information packet” containing details like mouse position, key pressed, and more. 🔹 Part 2: The Three Phases of an Event Event Bubbling: Events rise from the deepest element (child) up to its ancestors (parent → document). Event Capturing: The reverse — events travel from the top (document) down to the target. Visualizing Flow: Understanding how the browser processes events step by step helps debug like a pro. Control the Flow: Use event.stopPropagation() to prevent events from bubbling further when needed. 🧠 🔹 Part 3: The Event Delegation Pattern What Is It? Instead of adding listeners to multiple elements, attach one listener to a parent element. Why It’s Powerful: Better performance and easier management, especially for dynamic content. Key Tools: event.target → The actual element clicked. event.currentTarget → The element the listener is attached to. Real-World Example: Building an interactive to-do list where all items respond to clicks — with just one event listener! ✅ 🎯 Takeaway: Events are the heartbeat of interactive web apps. Understanding how they flow, bubble, and delegate gives you total control over your UI. #Day32 #JavaScript #WebDevelopment #Frontend #DOMEvents #EventHandling #CodingJourney #LearnInPublic #JS #Programming #CoderArmy #RohitNegi
To view or add a comment, sign in
-
-
“Don’t manipulate the DOM directly.” They said But no one told you why. But no one tells you why ? That one line confused thousands of developers. Frustration builds. Your code breaks. And suddenly you’re debugging your own logic . Sounds familiar right? A few months ago a junior developer I was mentoring reached out. “React just hates me. I didn’t even change anything but everything disappeared.” He wasn’t wrong. He was just fighting the wrong enemy. React wasn’t the problem. The real issue was that he touched the DOM manually without realizing React was already managing it. See, modern frameworks like React or Vue have a virtual DOM. They control updates automatically. When you manipulate the DOM yourself, you break their system. It’s like fixing a car engine while it’s still running. But here’s the twist ➝ Direct DOM manipulation isn’t bad. It’s just misunderstood. If you’re working with pure JavaScript or you need to handle animations, modals or third-party elements. it’s not just okay…it’s necessary. The difference? Experts know when to do it and why. Beginners do it everywhere and break everything. Frameworks automate the “how.” But great developers master the “why.” Because clean code isn’t about rules. It’s about reason. ↳ Want a short visual guide that shows exactly when to manipulate the DOM (and when to let React handle it)? Comment “DOM” below and I’ll share it with you. #FrontEnd_Developer #React #Digital_Marketing #Web_Development #JavaScript
To view or add a comment, sign in
-
#React Hooks Deep Dive: #useEffect vs #useLayoutEffect Ever wondered what actually happens between React re-rendering and what you see on the screen? Here’s the sequence — simplified and visual 👇 ⚛️ When React updates your component: 1️⃣ Render (Reconciliation) React calls your component function and prepares virtual DOM updates — in memory. 2️⃣ Commit Phase React applies those updates to the real DOM — but nothing is visible yet. 3️⃣ useLayoutEffect runs now This hook fires after the DOM updates but before the browser paints. 👉 Perfect for measuring or synchronously modifying the DOM. 4️⃣ 🎨 Browser Paints The browser finally draws the UI — the user now sees the result. 5️⃣ ⏱️ useEffect runs This happens after paint, great for async tasks like fetching data, logging, etc. 💡 Key takeaway: useLayoutEffect runs before the component is rendered on screen (painted), but after the DOM has been updated. #ReactJS #JavaScript #Frontend #WebDevelopment #ReactHooks #useEffect #useLayoutEffect #WebPerformance
To view or add a comment, sign in
-
95% of developers can’t clearly explain how JavaScript executes code. If you don’t understand the Event Loop, you don’t truly grasp JS. ➤ Complete JavaScript Event Loop Breakdown 𝗧𝗵𝗲 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸: Last-In-First-Out (LIFO) structure Stores currently running function contexts Functions are pushed when called Functions are popped when finished JavaScript runs on a single thread 𝗪𝗲𝗯 𝗔𝗣𝗜𝘀 (𝗕𝗿𝗼𝘄𝘀𝗲𝗿-𝗦𝘂𝗽𝗽𝗹𝗶𝗲𝗱): 6. setTimeout / setInterval – timer APIs 7. fetch / XMLHttpRequest – network requests 8. DOM events – click, scroll, keyboard 9. Promise resolution handled externally 10. All of these run outside the JS engine 𝗧𝗵𝗲 𝗤𝘂𝗲𝘂𝗲𝘀: 11. Callback Queue (Macrotask): setTimeout, DOM events, I/O callbacks 12. Microtask Queue: Promise.then, queueMicrotask, MutationObserver 13. Animation Frame Queue: requestAnimationFrame 𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗣𝗿𝗼𝗰𝗲𝘀𝘀: 14. Check if call stack is empty 15. If not, continue executing current code 16. If empty, run all microtasks first 17. Render updates if needed (60fps target) 18. Execute one macrotask from callback queue 19. Repeat the process endlessly 𝗣𝗿𝗶𝗼𝗿𝗶𝘁𝘆 𝗢𝗿𝗱𝗲𝗿: 22. Synchronous code executes immediately 23. Microtasks (Promises, queueMicrotask) 24. Animation frames (requestAnimationFrame) 25. Macrotasks (setTimeout, setInterval) 𝗖𝗼𝗺𝗺𝗼𝗻 𝗠𝗶𝘀𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴𝘀: 26. setTimeout(fn, 0) is not instant 27. Promises resolve asynchronously 28. async/await is just Promise syntax sugar 29. Event loop never stops 30. Long-running code blocks everything 𝗥𝗲𝗮𝗹-𝗪𝗼𝗿𝗹𝗱 𝗜𝗺𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀: 31. Heavy computation can block UI updates 32. Use Web Workers for CPU-intensive tasks 33. Split large tasks with setTimeout or requestIdleCallback 34. Promises always run before macrotasks 35. Understanding this helps debug async issues and race conditions Master the Event Loop and most JavaScript mysteries vanish. #JavaScript #EventLoop #AsyncJS #WebDevelopment #FrontendDev #CodingTips #Programming #Microtasks #Macrotasks #JS #DeveloperLife #TechTips #AsyncProgramming
To view or add a comment, sign in
-
-
🚀 JavaScript Tab Functionality Practice — Small Step, Big Learning! Today I practiced building a Tab Switching feature using pure JavaScript — focusing on DOM manipulation, event handling, and clean UI interaction. This hands-on mini project helped me understand how tabs dynamically show and hide content sections — a core concept for building interactive web interfaces. ✅ Learned about: querySelector and forEach usage for DOM selection Managing active classes dynamically Writing clean, reusable code for better scalability 💻 Pushed the project on GitHub for review & version control. 👉 Check it out here: [ https://lnkd.in/gjMWCFu6 ] Every small project adds up — one step closer to becoming a stronger Frontend Developer. 🌱 #JavaScript #WebDevelopment #FrontendDeveloper #CodingPractice #GitHub #LearningInPublic #100DaysOfCode #DeveloperJourney #CleanCode #UIUX #Tech
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development