Event Delegation

Handle events on parent element

IntermediateTopic: Events Programs
Back

JavaScript Event Delegation Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Basic event delegation
const list = document.getElementById('myList');

// Instead of adding listener to each item
list.addEventListener('click', function(e) {
    if (e.target.tagName === 'LI') {
        console.log('List item clicked:', e.target.textContent);
        e.target.classList.toggle('active');
    }
});

// Method 2: Dynamic content
const container = document.getElementById('container');

container.addEventListener('click', function(e) {
    if (e.target.classList.contains('button')) {
        console.log('Button clicked:', e.target.id);
    }
});

// Add new buttons dynamically - they work automatically!
function addButton(text) {
    const btn = document.createElement('button');
    btn.className = 'button';
    btn.textContent = text;
    container.appendChild(btn);
}

// Method 3: Multiple selectors
container.addEventListener('click', function(e) {
    if (e.target.matches('.delete-btn')) {
        deleteItem(e.target.dataset.id);
    } else if (e.target.matches('.edit-btn')) {
        editItem(e.target.dataset.id);
    } else if (e.target.matches('.view-btn')) {
        viewItem(e.target.dataset.id);
    }
});

// Method 4: Closest method
container.addEventListener('click', function(e) {
    const card = e.target.closest('.card');
    if (card) {
        console.log('Card clicked:', card.dataset.id);
    }
});

// Method 5: Event delegation with data attributes
const table = document.getElementById('dataTable');

table.addEventListener('click', function(e) {
    const row = e.target.closest('tr');
    if (row) {
        const id = row.dataset.id;
        const action = e.target.dataset.action;
        
        if (action === 'delete') {
            deleteRow(id);
        } else if (action === 'edit') {
            editRow(id);
        }
    }
});
Output
// Output depends on user interaction

Understanding Event Delegation

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

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents