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" draggable="true">
<p> Something here </p>
</section>
<section id="2" 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 ?
CodePudding user response:
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.
