Event Delegation in JavaScript

Are you worried about many handlers in your software code? Many handlers are creating so many events? As a Software Developer, you will try to write less amount code with more minor events. The event Delegation in JavaScript is the best solution for you.

Let me explain to you Event Delegation in JavaScript:

As a pattern, it manages all events created in code very efficiently without adding any further listeners. You don’t need to add any additional elements too. You can easily add an event listener to a particular parent. Then you can call that specific target by using these declared properties. Event delegation is the most famous patent event handler. It helps users append a single event to a parent element that matches the selector. 

The main steps are:

1. Need to add handler on a container

2. Add the event.target source.

3. Even the handler works to manage.

In the given below situations, you may try Event Delegation:

  1. Once you face events at a higher level, you can try event propagation ( bubbling) through Event Delegation in JavaScript. This bubbling process will manage the different elements. You can attach a single event for any single element. This element should exist in the present or may in the future.
  1. Once you have lots of elements to handle similarly, you should not assign a handler to each element. You can set one single handler for common elements.
  1. Suppose you want to make new menu buttons: save, search or load. Then, in general, you can add a handler to each menu button, but here easily, you can add a single handler for the whole menu buttons:
<button data-action="save">Click to Save</button>

Before working with Event Delegation in JavaScript, have a look at different phases:

Event delegation_1

A. Capturing phase: The moment an event will go down to the element, it is called capturing phase.

B. Target phase: Once the element reaches the element, it is called the Target phase.

C. Bubbling phase: Once the events bubble up from the element, it is called the Bubbling phase.

D. Event.target: You can get event.target in the handler to check which event is running now.

E. event.eventPhase: This phase helps determine which phase of the event is currently executed.

F. event.currentTarget: You can fix up the current target of the event by using this phase.

[Also Read, JavaScript Event Loop]

Let’s check out one example of event delegation:

Log a message to the console when you click the list item. Once you select the list item then please implement addEventListener() method in your JavaScript code:

HTML Code:
<ul class="list">
        <li id="list-item1">list item 1</li>
        <li id="list-item2">list item 2</li>
        <li id="list-item3">list item 3</li>
        <li id="list-item4">list item 4</li>
</ul>
    
JS Code:
<script>
document.querySelector('#list-item1').addEventListener('click', 
    function(e){
        console.log(e.target.textContent)
    }
)
document.querySelector('#list-item2').addEventListener('click', 
    function(e){
        console.log(e.target.textContent)
    }
)
document.querySelector('#list-item3').addEventListener('click', 
    function(e){
        console.log(e.target.textContent)
    }
)
document.querySelector('#list-item4').addEventListener('click', 
    function(e){
        console.log(e.target.textContent)
    }
)
</script>

When we do have a large number of the event handler, that time the event handler can impact straight to the following points:  

  1. Every handler is also an object as a usual function that takes things in memory more, which will slow the process.
  1. All event handlers will take more time due to delays in interactive pages.

We can solve this issue by using an event handler.

We usually follow three steps when implementing event delegation:

First Step: Declare the parent element to observe other events. Example:

<ul class=”list”></ul>

Second Step: Now you need to attach the event listener to this newly created parent.

Example of Use this syntax to attach elements:

document.querySelector(‘.list’).addEventListener(‘click’, handler)

Now the listener starts working on the list due to the bubbling phase.

Third Step: Always select the target by the event.target

The handler function will call the event object because of the list item is clicked. It depends upon the dispatched event.

HTML Code:
<ul class="list">
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
        <li>list item 4</li>
</ul>

JS Code:
document.querySelector('.list').addEventListener('click', 
    function(e){
        if(e.target.tagName === 'LI'){
            console.log(e.target.textContent)
        }
    }
)

All the patterns are organized adequately due to this event delegation steps in place of attaching a listener to every list item like earlier in not required anymore.

[Also Read, JavaScript Coding Interview Questions and Answers]

Let’s have a look at the benefits of Event Delegation:

A. Save memory

B. Simple initialization

C. Less code

D. DOM modification is easier

Conclusion:

JavaScript Event Delegation is the most valuable pattern to listen to various events running on multiple elements. This is very helpful for DOM(Document Object Model) events. The basic standard algorithm is:

1. Every container has one single handler.

2. Test the event target and fix it up.

3. All events running inside an element should bundle in the same event.

0 Shares:
You May Also Like