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

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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