Understanding JavaScript Event Delegation Technique (original) (raw)

Skip to content

Summary: in this tutorial, you will learn how to use the JavaScript event delegation that adds a single event handler to the parent element instead of having to register multiple event handlers to the child elements.

Introduction to JavaScript Event Delegation

Suppose that you have the following menu:

`

`Code language: HTML, XML (xml)

To handle the click event of each menu item, you may add the corresponding click event handlers:

`let home = document.querySelector('#home'); home.addEventListener('click',(event) => { console.log('Home menu item was clicked'); });

let dashboard = document.querySelector('#dashboard'); dashboard.addEventListener('click',(event) => { console.log('Dashboard menu item was clicked'); });

let report = document.querySelector('#report'); report.addEventListener('click',(event) => { console.log('Report menu item was clicked'); }); `Code language: JavaScript (javascript)

In JavaScript, if you have a large number of event handlers on a page, these event handlers will directly impact the performance because of the following reasons:

To solve this issue, you can leverage the event bubbling.

Instead of having multiple event handlers, you can assign a single event handler to handle all the click events:

`let menu = document.querySelector('#menu');

menu.addEventListener('click', (event) => { let target = event.target;

switch(target.id) {
    case 'home':
        console.log('Home menu item was clicked');
        break;
    case 'dashboard':
        console.log('Dashboard menu item was clicked');
        break;
    case 'report':
        console.log('Report menu item was clicked');
        break;
}

});`Code language: JavaScript (javascript)

How it works.

The way that we handle the too-many-event-handlers problem is called the event delegation.

The event delegation refers to the technique of using event bubbling to handle events at a higher level in the DOM than the element on which the event originated

When it is possible, you can have a single event handler on the document that will handle all the events of a particular type. By doing this, you gain the following benefits:

Summary

Was this tutorial helpful ?