loading...

How to add event listener to dynamically added elements

trilemaestro92 profile image Tri Nguyen ・2 min read

What is up fellow coder.
Welcome to my second installment of "How to" guides
Thank you for checking out my article on learning how to add event listener to dynamically added element.

Lets get right into it!

First add a element

Alt text of image

Alt text of image

The breakdown

  1. I have a simple HTML document that includes a button named "click me" and also an empty div. Both element have an id.

  2. In the JavaScript file, in line 8 I made a render function that should append a string to an element, which in this case will be on the empty div from earlier.

  3. Therefore line 1-5 it's just me making a function called "addButton" that uses render function to make a new button called "new button". Line 15 is the event listener that adds a new button every time I click on "click me".

Now that we can add a button. How can we add an event listener to that new button ?

Let me show you DE WAY

Alt text of image

The breakdown

  1. The answer starts on line 16. First I create a event listener for the #content which if you remember is the main selector id for the empty div on the html document .

  2. Then for the on function the first parameter is action value "click", the second parameter will be a child-selector name which in this case the class of the new button added(see line 3). The third parameter is a callback value, in which I made a function that will turn the new button background yellow.

EZ PZ!!

As you can see I was able to add an event listener on my "new button", if when I click on the new button it will change its background to yellow.

Nice Gibberish...but what is the point???

Well since you now know the basics on how to add an event listener to a dynamically added element. You don't need me to tell you of all the possibility you can use this function with or how commonly this is used. Just think any time you post something on Facebook, Twitter, or LinkedIn you are essential dynamically adding a element to a page. Thus if you can't add a event listener to them how are you able to comment, like, or react to those post.

Discussion

pic
Editor guide
Collapse
hugo__df profile image
Hugo Di Francesco

This pattern is usually called event delegation (for anyone looking for more info).

Nice simple explanation of a scenario where you would need it.

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
trilemaestro92 profile image
Tri Nguyen Author

Yep I thanks, I will