Event Propagation in JavaScript Explained

𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗘𝘃𝗲𝗻𝘁 𝗣𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁- Ever clicked a button inside a card and wondered what actually happens behind the scenes? That is event propagation at work. 𝗘𝘃𝗲𝗻𝘁 𝗽𝗿𝗼𝗽𝗮𝗴𝗮𝘁𝗶𝗼𝗻 describes how a single event travels through the DOM hierarchy. 𝗥𝗲𝗮𝗹-𝗪𝗼𝗿𝗹𝗱 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: Imagine a parent card component containing multiple child buttons. When you click a button: • The button receives the event first • The event then moves to the parent card • It continues upward through the DOM 𝐓𝐡𝐢𝐬 𝐦𝐨𝐯𝐞𝐦𝐞𝐧𝐭 𝐨𝐟 𝐞𝐯𝐞𝐧𝐭𝐬 𝐢𝐬 𝐩𝐫𝐨𝐩𝐚𝐠𝐚𝐭𝐢𝐨𝐧. 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝟯 𝗽𝗵𝗮𝘀𝗲𝘀: 1. 𝗖𝗮𝗽𝘁𝘂𝗿𝗶𝗻𝗴 𝗣𝗵𝗮𝘀𝗲 (Top --> Down): The event travels from the root element toward the target. 2. 𝗧𝗮𝗿𝗴𝗲𝘁 𝗣𝗵𝗮𝘀𝗲: The event reaches the exact element that was clicked. 3. 𝗕𝘂𝗯𝗯𝗹𝗶𝗻𝗴 𝗣𝗵𝗮𝘀𝗲 (Bottom --> Up): The event bubbles back up to the root. Use 𝐞𝐯𝐞𝐧𝐭.𝐬𝐭𝐨𝐩𝐏𝐫𝐨𝐩𝐚𝐠𝐚𝐭𝐢𝐨𝐧() to prevent parent handlers from executing. #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #Programming #TechLearning #SoftwareEngineering #SystemDesign #DOM #FrontendInterview

  • text

To view or add a comment, sign in

Explore content categories