Course contentsShow
← Web Development
Lesson 760 of 2,98213. DOM EventsFree lesson

Basic Delegation Pattern

Implementing a simple delegated listener using event.target to identify which child element triggered the event.

Basic Delegation Pattern

You'll learn how to implement a simple event delegation pattern by checking event.target to identify which child element triggered the event.

The Core Idea

Instead of attaching separate event listeners to each child element, you attach one listener to a parent element and use event.target to determine which specific child was clicked (or interacted with). This is event delegation in action.

Think of it like a teacher monitoring a classroom. Rather than standing next to each student individually, the teacher stays at the front and responds based on which student raises their hand—checking who triggered the need for attention.

How It Works

When you add a listener to a parent element, any event that bubbles up from its children can be intercepted. Inside your handler function, you check event.target to see which element actually received the interaction:

const parentList = document.querySelector('ul');

parentList.addEventListener('click', function(event) {
  // event.target tells us which <li> was clicked
  if (event.target.tagName === 'LI') {
    console.log('You clicked:', event.target.textContent);
  }
});

Here, even though we attached the listener to the <ul>, we can handle clicks on individual <li> elements by inspecting event.target.

Why This Matters

  • Fewer listeners: One listener instead of dozens
  • Dynamic content: Works even for elements added after the listener is attached
  • Better performance: Less memory overhead and setup code

Key Takeaway: The basic delegation pattern uses a single listener on a parent element and checks event.target to identify which child triggered the event, making your code more efficient and flexible.