Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
Add eventListener to dynamic element

I have a function which gets data from a php file and insert them in the html. The problem is that I need to add drag & drop event listeners to all these new inserted elements, and I don't know how I can do so.

Here is my function :

    function getTask() {

  //create -> Ajax request
  const req = getHttpRequest();
  req.open("GET", "../php/task.php");

  req.onload = function() {

    const result = JSON.parse(req.responseText);

    const html   = result.map(function(task){

      return taskHTML(task.title);

    }).join('');

    const thread = document.querySelector('#list-task');
    thread.insertAdjacentHTML('beforeend', html);

  }

  req.send();

}

And I would like to add these event listeners to my new inserted element :

  task.addEventListener('dragstart', dragStart, false);
  task.addEventListener('dragenter', dragEnter, false);
  task.addEventListener('dragleave', dragLeave, false);
  task.addEventListener('dragover', dragOver, false);
  task.addEventListener('drop', dragDrop, false);
  task.addEventListener('dragend', dragEnd, false);

So I tried doing this :

    const secondFunction = async () => {
  const result = await getTask();
  tasks = document.querySelectorAll('.task');
  tasks.forEach(task => {
  task.addEventListener('dragstart', dragStart, false);
  task.addEventListener('dragenter', dragEnter, false);
  task.addEventListener('dragleave', dragLeave, false);
  task.addEventListener('dragover', dragOver, false);
  task.addEventListener('drop', dragDrop, false);
  task.addEventListener('dragend', dragEnd, false);

  });
}
secondFunction();

But it doesn't work. I also looked at event delegation but I don't think it applies in my case since it's drag and drop events and not click events. So is there a way to attached these events to my new inserted elements ?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda