event_delegation

What is event delegation?

  • Profile picture of Mcs
  • by Mcs July 2, 2025

Event delegation is a programming pattern in JavaScript where a single event listener is attached to a parent element instead of multiple event listeners on individual child elements. This works because of event bubbling, where events triggered on child elements propagate (or "bubble up") to their ancestors.

Why use event delegation?

  • Performance: Fewer event listeners mean less memory usage and better performance.
  • Dynamic content: It handles events on elements that are added to the DOM after the event listener is attached.

Example

Suppose you have a list of items and want to respond to clicks on any item:

HTML:

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>

Without delegation (inefficient for large/dynamic lists):

document.querySelectorAll('#myList li').forEach(item => {
     item.addEventListener('click', () => {
       console.log('Item clicked');
     });
});

With event delegation (better):

document.getElementById('myList').addEventListener('click', function(event) {
     if (event.target.tagName === 'LI') {
        console.log('Item clicked:', event.target.textContent);
     }
});

In this delegated version, a single listener on the <ul> handles clicks for all <li> elements—even ones added later.

Key Points:

  • Relies on event bubbling.
  • Use event.target to find which child was actually clicked.
  • Often used for lists, tables, or any UI elements where children are dynamic.

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.