← Back to Chapters

jQuery Event Delegation

? jQuery Event Delegation

? Quick Overview

Event Delegation is a powerful jQuery technique where you attach an event handler to a parent element instead of attaching it to individual child elements. This works especially well for dynamically added elements.

? Key Concepts

  • Uses event bubbling
  • Improves performance
  • Works for dynamically created elements
  • Implemented using .on()

? Syntax / Theory

Instead of binding events directly to elements, you bind them to a parent that exists at page load. The event bubbles up and is handled at the parent level.

? View Code Example
// Syntax of event delegation
$(parentSelector).on(event, childSelector, function() {
// event handling logic
});

? Code Example(s)

? View Code Example
// Attach click event using delegation
$("#list").on("click", "li", function() {
// This will work for existing and future li elements
$(this).css("color", "red");
});

? Live Output / Explanation

Clicking on any list item (even dynamically added ones) will change its color to red because the event is handled by the parent element.

? Interactive Example

  • Initial Item 1 (Click me!)
  • Initial Item 2 (Click me!)

Notice: New items respond to clicks immediately without re-binding events.

? View Code Example
// Dynamically add list items and handle clicks
$("#addItem").click(function() {
$("#list").append("<li>New Item</li>");
});

? Use Cases

  • Handling events on dynamically added elements
  • Optimizing performance for large lists
  • Managing events in tables or menus

✅ Tips & Best Practices

  • Always delegate to the closest static parent
  • Avoid delegating too high in the DOM
  • Prefer .on() over older methods like .delegate()

? Try It Yourself

  • Create a dynamic to-do list using event delegation
  • Add hover and click events to table rows
  • Compare delegated vs direct event binding