Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
drag drop doesn't work for dynamically inserted element

I have a div which is a list of sections that are draggable.

I then have a drag and drop script which looks like this:

const 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);

});



function dragStart(e) {
  //do something
};

function dragEnter(e) {
  //do something
}

function dragLeave(e) {
  //do somehting
}

function dragOver(e) {

  //do something
}

function dragDrop(e) {
  //do something 
}

function dragEnd(e) {

  //do something
}
<div id="list">
  <section id="1" class="task" draggable="true">
    <p> Something here </p>
  </section>

  <section id="2" class="task" draggable="true">
    <p> Something here </p>
  </section>

  ...

</div>

Everything works perfectly (every section can be drag & drop).

Yet if instead of having a static HTML I do: document.getElementById('list').insertHTML(//my draggable sections) then my js script doesn't seems to work anymore. I can't drag & drop my sections.

I don't understand why, it seems like inserting the sections dynamically change something but I don't understand what... Is there a way to fix this problem ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

by element.insertHTML() do you element.insertAdjacentHTML()?
Anyways, I would guess that there's an issue with code execution order, it's probably running

const tasks = document.querySelectorAll('.task');

before you change html inside .list element. This means that const tasks ends up being empty array(it's actually empty NodeList but doesn't metter here)

Also if you don't have any specific reason to use insertAdjacentHTML, I would recomend you to use appendChild instead.

UPD

Also, every time you add new items to your list you would have to add eventListeners to each node you added.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda