'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 ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
