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.
|
<div class="wrapper"> <div class="list-item">Static DOM Element(Click me)</div> </div> |
Let’s apply some Styling to above HTML block.
|
.list-item{ font-size: 18px; display:inline-block; text-transform : capitalize; border : 1px solid #ccc; padding : 10px; margin : 0 auto; } |
Finally, let’s attach a addEventListener to element with class list-item.
|
// Add event for existing DOM element document.querySelector(".wrapper .list-item").addEventListener("click",translateMe); function translateMe(event){ event.target.style.transform = "translateY(30px)"; event.target.style.color ="red"; } |
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 …