1

I have a code which is using Vanilla JS. Using a button I added dynamic content. But the problem is when I clicked a dynamically generated content, then it returns first click: 1 second click: 3 third click: 6 fourth click: 10

but it should be 1, 2, 3, 4

HTML Code Below:

<p>Add Content</p>
  <div class="dynamic-content">

JS file Below:

let counter = 1;
document.querySelector("p").addEventListener("click", function(){
  document.querySelector(".dynamic-content").innerHTML += `
    <span>My dynamic content - ${counter}</span>
  `;
  counter++;
});

document.querySelector("body").addEventListener("click", function(){
  let contentList = document.querySelectorAll(".dynamic-content span");
  if(contentList.length){
    contentList.forEach(function(el){
      el.addEventListener("click", function(event){
        console.log(event.target.innerText);
      });
    });
  }
});

Note: We can't use jQuery

v

Barmar
  • 741,623
  • 53
  • 500
  • 612
wpmarts
  • 532
  • 6
  • 8
  • 2
    No wonder, every time you click on the document body, you're adding a bunch of new listeners to the elements. – Teemu Jul 22 '20 at 12:44
  • 1
    It's almost never right to add event listeners inside another event listener. – Barmar Jul 22 '20 at 12:54
  • When you add a new span, just add an event listener to that span. Don't add the event listener to ALL spans every time. – Barmar Jul 22 '20 at 12:56
  • Or use event delegation so you don't need to add a new event listener every time. – Barmar Jul 22 '20 at 12:57

1 Answers1

1
let counter = 1;
document.querySelector("p").addEventListener("click", function(){
  const element = document.createElement("span") 
  element.innerHTML += `My dynamic content - ${counter}`;
  document.querySelector(".dynamic-content").appendChild(element)
  element.addEventListener("click", function(){
     console.log('element')
     // here logic
  })
  counter++;
});

https://www.w3schools.com/jsref/met_document_createelement.asp Try with document.createElement and then add the event to created element, in this solution you will add only one event to the HTML tag.

Maciej Trzciński
  • 181
  • 1
  • 2
  • 9