Adding Event Listeners to the future DOM elements using Event Bubbling 
Tags: javascript, web, frontend, dom
Published: 2019-07-11 10:27:54

---
title: Adding Event Listeners to the future DOM elements using Event Bubbling 
published: true
description: Ever wondered how one can attach event listeners to the elements that would be appended to DOM dynamically later in an application. This article talks about it and tries to come up with a solution using the concept of Event Delegation
tags: javascript,web,frontend,DOM
cover_image: https://images.unsplash.com/photo-1476611317561-60117649dd94?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80
---
### Brief Intro :
Before I get into details, let me answer the primary questions so that you need not waste time reading the whole article
- Who is this for? 
   - Any native javascript developer who has beginner knowledge of DOM API
- What will I learn?
   - You will be learning how to handle the use cases where you have to add an event listener to an element that might be added to UI in the future workflow. In short, you will be learning `Event Delegation`


### Problem Statement :

It all started when I was developing a simple MVC to-do app using vanilla javascript. I came across a requirement of listening to the click event of the task item that is going to be added to the UI when the user clicks on 'Add Task Button'.

Then I started to wonder, how can one add the event listeners to the elements that will be added in the future workflow? 

Generally, one can add an event listener to an element that already exists in the DOM in the following way

```javascript
 let taskDOMElement = document.querySelector('#task');
 taskDOMElement.addEventListener('click',clickHandler,false);
 function clickHandler()
 {
    //handle the event
 }
```
But in order to add the event listeners to the elements that are going to be appended to DOM in the future, we have to use the concept of `Event Bubbling` where the events bubble from the target Element to the parent Element invoking their respective event handlers

### Solution :
- First, we have to figure out the nearest non-dynamic element in our DOM that will not be changed in our workflow(in my case it is body element)
```javascript
let rootElement = document.querySelector('body');
```
- Then attach the same event listener to that element you want to listen from the future element(in my case, it is click event)
```javascript
let rootElement = document.querySelector('body');
rootElement.addEventListener('click',function(event){},true);
```
- Now check if the event target matches your selector(in my case its a li tag)
```javascript
let rootElement = document.querySelector('body');
rootElement.addEventListener('click',function(event){
let targetElement = event.target
let selector = 'li';
if(targetElement.match(selector) {
//logic for handling the click event of li tag
 }
},true);
```
- But to be more precise , we have to traverse from the target to the root Element for capturing the event 
```javascript
rootElement.addEventListener('click',function(event){
let targetElement = event.target
let selector = 'li';
while(targetElement != null) {
if(targetElement.match(selector) {
   //logic for handling the click event of li tag
   return;
  }
  targetElement = targetElement.parentElement;
 }
},true);
```
- So after few touchups,here is the generalised function to handle the event listeners of future elements
```javascript
addCustomEventListener: function (selector, event, handler) {
        let rootElement = document.querySelector('body');
        //since the root element is set to be body for our current dealings
        rootElement.addEventListener(event, function (evt) {
                var targetElement = evt.target;
                while (targetElement != null) {
                    if (targetElement.matches(selector)) {
                        handler(evt);
                        return;
                    }
                    targetElement = targetElement.parentElement;
                }
            },
            true
        );
    }

//adding the Event Listeners to all the li tasks
addCustomEventListener('li#task','click',taskClickHandler);

```
- So, this is how you can attach event listeners to the future elements i.e., elements that are added dynamically in future

###Links
 - [Event Delegation](https://javascript.info/event-delegation)
 - [David Walsh about Event Delegation](https://davidwalsh.name/event-delegate)

### Credits
 Cover Image by [Alejandro Alvarez](https://unsplash.com/@a2foto) 

### Conclusion:

I hope you find this article useful and helpful at some point in time. I would love to hear your feedback on the article and discuss more on this