DEV Community

aliplutus
aliplutus

Posted on

How to get the distance of closest element while dragging over?

I'm trying to create a sortable tree in which when I drop an element ender another one it will resort ender and when I drop it above it will be sorted above, and when it dropped on the element it will resort as a child element. I create the following formula, but it is no reliable because offset=the distance between mouse position and between the original position of the dragged object.

const box = draged.getBoundingClientRect()
const offset = e.clientY - box.top - (box.height / 2)

So, how to get the relative option of between the dragged element and the draggedOver element.

fullcode

Top comments (1)

Collapse
 
aliplutus profile image
aliplutus • Edited

Solved

onDragOver={e => {
            e.preventDefault()
            const box = e.target.getBoundingClientRect()
            const offset = e.clientY - box.top - (box.height / 2)
            console.log(offset)

            setItems(pre => {
              return arrayMove(pre, eval(draged.id), index)
            })

          }}