Event Delegation in JavaScript
Handle events on parent element
IntermediateEvents ProgramsExample 4 of 10
event-delegation.js
1// Method 1: Basic event delegation2const list = document.getElementById('myList');34// Instead of adding listener to each item5list.addEventListener('click', function(e) {6 if (e.target.tagName === 'LI') {7 console.log('List item clicked:', e.target.textContent);8 e.target.classList.toggle('active');9 }10});1112// Method 2: Dynamic content13const container = document.getElementById('container');1415container.addEventListener('click', function(e) {16 if (e.target.classList.contains('button')) {17 console.log('Button clicked:', e.target.id);18 }19});2021// Add new buttons dynamically - they work automatically!22function addButton(text) {23 const btn = document.createElement('button');24 btn.className = 'button';25 btn.textContent = text;26 container.appendChild(btn);27}2829// Method 3: Multiple selectors30container.addEventListener('click', function(e) {31 if (e.target.matches('.delete-btn')) {32 deleteItem(e.target.dataset.id);33 } else if (e.target.matches('.edit-btn')) {34 editItem(e.target.dataset.id);35 } else if (e.target.matches('.view-btn')) {36 viewItem(e.target.dataset.id);37 }38});3940// Method 4: Closest method41container.addEventListener('click', function(e) {42 const card = e.target.closest('.card');43 if (card) {44 console.log('Card clicked:', card.dataset.id);45 }46});4748// Method 5: Event delegation with data attributes49const table = document.getElementById('dataTable');5051table.addEventListener('click', function(e) {52 const row = e.target.closest('tr');53 if (row) {54 const id = row.dataset.id;55 const action = e.target.dataset.action;5657 if (action === 'delete') {58 deleteRow(id);59 } else if (action === 'edit') {60 editRow(id);61 }62 }63});
Output
// Output depends on user interaction
What's going on
Event delegation handles events on parent.
Benefits
Works with dynamic content
Better performance
Less memory usage
Single event listener
How It Works
Add listener to parent
Check event.target
Handle based on target
Use Cases
Dynamic lists
Tables with actions
Cards and containers
Forms with dynamic fields
Best Practices
Use closest() for nested elements
Check target with matches()
Use data attributes for actions