My Code (Used one from web devs simplifed video) only works on elements already present and coded in HTML file , but not on ones that are later added dynamically from inputs and when I try to Drag them they throw off this error Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.,
this is the code :
const draggable = document.querySelectorAll('.output-list-item');
draggable.forEach(draggable =>{
draggable.addEventListener('dragstart', ()=>{
draggable.classList.add('dragging');
})
draggable.addEventListener('dragend',()=>{
draggable.classList.remove('dragging');
})
})
outputUl.addEventListener('dragover',(e)=>{
e.preventDefault();
const afterElement = getDragAfterElement(outputUl, e.clientY)
const draggable = document.querySelector('.dragging');
if(afterElement === null){
outputUl.appendChild(draggable)
}else{
outputUl.insertBefore(draggable, afterElement)
}
})
function getDragAfterElement(container,y){
const draggableElements = [...container.querySelectorAll('.output-list-item:not(.dragging)')]
return draggableElements.reduce((closest,child)=>{
const box = child.getBoundingClientRect();
const offset = y-box.top - box.height /2
if(offset < 0 && offset > closest.offset){
return {offset: offset, element:child}
}else{
return closest;
}
},{offset:Number.NEGATIVE_INFINITY}).element
}