The blog provides the details on the usage of event delegation in JavaScript. The Event Delegation is most powerful event handling pattern which is implemented using the Event Capturing and Event Bubbling in JavaScript.
Read the blog to understand Event Bubbling and Capturing in JavaScript
When an event(button click) is triggered on an element, then the event bubbles up from the originating element to the top of the DOM tree (reaching to that element’s ancestors) which is known as event bubbling. The target element is the element that actually caused the event to trigger and is stored in a property of the event object.
Event Delegation allows to add an event handler to an element, wait for an event to bubble up from a child element and determines the target element which initiated the event.
Event Delegation example in JavaScript
<html> <head> </head> <body> <div id="menu"> <button data-action="save">Save</button> <button data-action="load">Load</button> <button data-action="search">Search</button> </div> <script> class Menu { constructor(e) { this._elem = e; e.onclick = this.onClick.bind(this); // (*) } save() { alert('Save button is Clicked'); } load() { alert('Load button is Clicked'); } search() { alert('Search button is Clicked'); } onClick(event) { let action = event.target.dataset.action; if (action) { this[action](); } }; } new Menu(menu); </script> </body> </html>
Behavior pattern in event delegation
The Event Delegations also support the “behavior” pattern. The below given is the example where the event is triggered based on the attribute behavior
<html> <head> </head> <body> Counter: <input type="button" value="1" data-counter> <script> document.addEventListener('click', function(event) { if (event.target.dataset.counter != undefined) { // if the attribute exists... event.target.value++; } }); </script> </body> </html>
References: https://javascript.info/event-delegation