Because events in JavaScript ""bubble"" up the DOM tree, you can attach a single event listener to the parent container and use event.target to figure out which child was clicked. JavaScript // Attach ONE listener to the parent <ul> document.getElementById('item-list').addEventListener('click', (event) => { // Check if the clicked element was a button if (event.target.tagName === 'BUTTON') { const itemId = event.target.dataset.id; console.log(`Item ${itemId} clicked!`); } }); This uses drastically less memory and automatically handles new items added to the list dynamically—no need to attach new listeners when the DOM updates! #JavaScript #WebPerformance #CodingInterviews #FrontendDev #TechTips"
Attach single event listener to parent container with JavaScript
More Relevant Posts
-
📚 Today I Learned: Scope Chain in JavaScript The scope chain in JavaScript is used to resolve variable values. When a variable is used, JavaScript looks for it in a specific order. 🔹 How it works: 1️⃣ JavaScript first checks the current scope. 2️⃣ If the variable is not found, it checks the outer (parent) scope. 3️⃣ This process continues until it reaches the global scope. 💻 Example: let a = 10; function outer() { let b = 20; function inner() { let c = 30; console.log(a, b, c); } inner(); } outer(); ✅ The inner() function can access c, b, and a because of the scope chain. #javascript #webdevelopment #frontenddeveloper #learninginpublic
To view or add a comment, sign in
-
From basic tags to advanced frameworks, here is the breakdown: ✅ Days 1-20: The Foundations (HTML/CSS) ✅ Days 20-40: The Engine (JavaScript/React) ✅ Days 40-70: Real-world Application & Design ✅ Days 80-100: Optimization & Polish Which stage do you find the most challenging? For me, it was definitely mastering Advanced JS! #TechCommunity #CodeNewbie #FrontendDeveloper #Roadmap
To view or add a comment, sign in
-
-
What is Hoisting in JavaScript? Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before execution. This means you can sometimes use variables or functions before they are declared in the code. 1️⃣ Variable Hoisting with var console.log(a); // undefined var a = 10; Behind the scenes, JavaScript interprets it like this: var a; console.log(a); // undefined a = 10; 👉 The declaration is hoisted, but not the assignment. 2️⃣ Hoisting with let and const console.log(a); // ❌ ReferenceError let a = 10; Variables declared with let and const are hoisted but placed in the Temporal Dead Zone (TDZ), meaning they cannot be accessed before initialization. 3️⃣ Function Hoisting Function declarations are fully hoisted. greet(); function greet() { console.log("Hello JavaScript"); } This works because the entire function definition is hoisted. #javascript #webdevelopment #frontenddeveloper #mernstack #codinginterview #softwareengineering
To view or add a comment, sign in
-
💡 JavaScript Practice — Counting Vowels A small problem, but a good test of logic: 👉 Count the number of vowels in a string Here’s my solution: const str = "javascript"; const vowels = "aeiouAEIOU"; let count = 0; for (let letter of str) { for (let vowel of vowels) { if (letter === vowel) count++; } } console.log(count); 🧠 What this taught me: • How nested loops actually work in real scenarios • Breaking a problem into smaller steps • Writing simple, readable logic ⚡ Next step: I’ll try optimizing this (maybe using includes() or a better approach) If you have a cleaner or more efficient solution, I’d love to see it. #JavaScript #ProblemSolving #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
Today I practiced a small JavaScript program to change the background color when a button is clicked. When the button is pressed, JavaScript triggers a function that changes the page’s background color using DOM manipulation. This helped me understand: ✔ Event handling ✔ onclick function ✔ DOM manipulation ✔ How JavaScript interacts with HTML & CSS Small practice, better understanding 🚀 #JavaScript #WebDevelopment #Frontend #CodingPractice #LearningJourney
To view or add a comment, sign in
-
The JavaScript "this" Trap 🪤🔥 The Puzzle: What is the output? 🤔 const obj = { name: "JS", getName() { console.log(this.name); } }; const fn = obj.getName; fn(); Output: undefined Why? 🧠 In JavaScript, this depends on HOW a function is called, not where it is written. Lost Context: const fn = obj.getName only copies the function reference. Standalone Call: When you call fn(), there is no object (no dot) before the function. Global Context: It now runs in the Global Context (window object). Since window.name is not "JS", it returns undefined. How to Fix? 🛠️ ✅ Use .bind(): const fn = obj.getName.bind(obj); ✅ Use .call(): fn.call(obj); ✅ Use Arrow Functions: They inherit this from the surrounding scope. Interview Tip: 💡 Always check the "Call Site." No dot before the function call (like fn()) usually means this is lost! #JavaScript #CodingTips #365DaysOfCode #InterviewPrep #WebDev #FullStack #mern #react #node
To view or add a comment, sign in
-
📊 Day 9 – Poll Answer & Explanation console.log(1 < 2 < 3); console.log(3 > 2 > 1); 🧠 Concept: Type Coercion & Comparison Evaluation in JavaScript In JavaScript, comparisons are evaluated **from left to right**. When a **boolean** is used in another comparison, JavaScript converts it to a **number**. true → 1 false → 0 🔍 Step-by-step explanation ✅ First Expression 1 < 2 < 3 Step 1 1 < 2 ✔️ true Step 2 true < 3 true → 1 1 < 3 ✔️ true Output: true ⚠️ Second Expression 3 > 2 > 1 Step 1 3 > 2 ✔️ true Step 2 true > 1 true → 1 1 > 1 ❌ false Output: false 🖨️ Final Output true false 🎯 Key Takeaway JavaScript **does not support chained comparisons like math**. 3 > 2 > 1 is evaluated as: (3 > 2) > 1 true > 1 1 > 1 false 💡 Tip: Use logical AND for correct comparison. console.log(3 > 2 && 2 > 1); // true #JavaScript #JSConcepts #TypeCoercion #TrickyQuestions #Frontend #PollAnswer
To view or add a comment, sign in
-
Today I practiced the difference between map(), filter(), and forEach() in JavaScript. map() creates a new array by transforming each element of the original array. filter() creates a new array with elements that satisfy a specific condition. forEach() simply runs a function for each element and does not return a new array. Understanding these methods makes working with arrays much easier and cleaner. #JavaScript #WebDevelopment #ArrayMethods #LearningJourney
To view or add a comment, sign in
-
⚡ Understanding the JavaScript Event Loop (Simplified) One concept that helped me understand JavaScript much better is the Event Loop. JavaScript is single-threaded, but it can still handle asynchronous operations like API calls, timers, and promises. How? Because of the Event Loop. In simple terms: 1️⃣ JavaScript executes synchronous code first (Call Stack). 2️⃣ Async tasks like setTimeout or API requests go to Web APIs. 3️⃣ Once completed, they move to the Callback Queue. 4️⃣ The Event Loop checks if the call stack is empty and pushes callbacks back for execution. This is why code like this works: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 0); console.log("End"); Output: Start End Async Task Even with 0 delay, async tasks wait until the call stack is empty. 💬 When did you first learn about the Event Loop? #JavaScript #WebDevelopment #FrontendDevelopment #AsyncProgramming
To view or add a comment, sign in
-
I recently built a Real-Time Character Counter using HTML, CSS, and JavaScript. The text area updates the character count as the user types and prevents input beyond the maximum limit. This small project helped me practice JavaScript event handling and DOM manipulation. Feel free to check it out and use the code for learning. #JavaScript #WebDevelopment #HTML #CSS #LearningByDoing #CodingJourney Live demo link: https://lnkd.in/gHNBqfN2 Github repository link: https://lnkd.in/geS37Eia
To view or add a comment, sign in
-
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