0

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
}
Muramasa
  • 1
  • 1
  • when you create new elements, bind `dragstart` and `dragend` to them just like you did to already existing elements – GrafiCode Oct 16 '22 at 16:08
  • `draggable.forEach(draggable =>{` you really should use a different naming scheme for the nested items in your nodelist, maybe something like `draggable.forEach(draggableItem =>{`. You also use that naming scheme again for a totally different query. IMHO this is a bad practice that can lead to confusion when trying to troubleshoot issues. – dale landry Oct 16 '22 at 16:09
  • i will change the names thx for pointing it out ^_^ – Muramasa Oct 16 '22 at 16:23
  • bind them to new elements how ? – Muramasa Oct 16 '22 at 16:23
  • should i do it with event bubbling ? – Muramasa Oct 16 '22 at 16:25

0 Answers0