Javascript : Event binding on Dynamically created element

Spread the love

Whenever we bind events to DOM element, events got attached with all elements which are there in DOM but same events will not get attached to any element which is added dynamically. in order to understand event binding, let’s consider a below DOM structure.

Let’s apply some Styling to above HTML block.

Finally, let’s attach a addEventListener to element with class list-item.

Now if i click on final link, it will translate 30px in Y-axis. You can test the same in Codepen here. Now let’s add a dynamic DIV element with class list item and wrap it inside element with class wrapper as follow.

Now another dynamic link will be created but click event will not work on same. For events to work on above element, you have to attach event Listener to newly created element. This can be done by adding below line of code to above object.

Now both the static as well as dynamic link will have event listener attached to it. For demo, you can check Codepen here.

 



Leave a Reply

Your email address will not be published. Required fields are marked *