Event delegation leverages event bubbling to handle events efficiently. Here's how to use it.
Event Bubbling Basics
Basic Event Delegation
Dynamic Elements
Multiple Actions
Table Handling
Form Handling
Keyboard Events
Drag and Drop
Event Delegation Utilities
Performance Benefits
Events That Don't Bubble
Best Practices
When to Use:
✓ Many similar elements
✓ Dynamic content
✓ Performance sensitive lists
✓ Shared behavior patterns
Implementation:
✓ Use closest() for nested elements
✓ Check element existence
✓ Use data attributes for actions
✓ Consider capture phase for non-bubbling events
Performance:
✓ Attach to closest common ancestor
✓ Keep selectors simple
✓ Avoid deep nesting checks
✓ Use event.target.matches() efficiently
Avoid:
✗ Delegating to document for everything
✗ Complex selector chains
✗ Forgetting stopPropagation implications
✗ Over-delegating simple cases
Conclusion
Event delegation improves performance and handles dynamic elements automatically. Use closest() for reliable element matching, data attributes for action identification, and remember to use capture phase for events that don't bubble. Delegate to the closest common ancestor, not always to document.