dragged items to correct target spot

13 Views Asked by At

I am making my to-do list items draggable. When the dragged element is 'over in the list'/'gets dragged down' it is added to the spot before target and target stays in the same spot. It also means that I can never drag items to the bottom of the list. Dragging upwards, everything is as it is supposed to be.

function handleDrop(e) {
    e.preventDefault();
    const draggedId = e.dataTransfer.getData('text/plain');
    const draggedElement = document.getElementById(draggedId);
    
    if (draggedElement && e.target !== draggedElement) {
        const position = e.target.compareDocumentPosition(draggedElement);
        if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
            e.target.parentNode.insertBefore(draggedElement, e.target);
        } else {
            e.target.parentNode.insertBefore(draggedElement, e.target);
        }
    }

    draggedElement.classList.remove('sortableList');
    saveData();
}

I have tried adding .nextSibling to the if statement, but it doesnt fix it and it ruins the upwards drag as well.

function handleDrop(e) {
    e.preventDefault();
    const draggedId = e.dataTransfer.getData('text/plain');
    const draggedElement = document.getElementById(draggedId);
    
    if (draggedElement && e.target !== draggedElement) {
        const position = e.target.compareDocumentPosition(draggedElement);
        if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
            e.target.parentNode.insertBefore(draggedElement, e.target.nextSibling);
        } else {
            e.target.parentNode.insertBefore(draggedElement, e.target);
        }
    }

    draggedElement.classList.remove('sortableList');
    saveData();
}
0

There are 0 best solutions below