Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!