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
I have a simple HTML document that includes a button named "click me" and also an empty div. Both element have an id.
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
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 .
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.
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.
Top comments (3)
This pattern is usually called event delegation (for anyone looking for more info).
Nice simple explanation of a scenario where you would need it.
Yep I thanks, I will