Search code examples
javascriptdrag-and-drop

How to release object after drag-drop in Javascript


I found this interesting example for a javascript Drag/Drop on https://codepen.io/islempenywis/pen/VXqJVY.

However, there is an issue with it that if you click on the top of the "TODO Item" rectangle, after drag (MouseDown + Drag + MouseUp) it is not possible to drop this item; it sticks to the cursor and travels with it :/

MouseUp is a simple function, nothing fancy :

function onMouseUp(e, item) {
  isMouseDown = false;
  item.style.backgroundColor = "#F44336";
}

Since I can replicate it with Chrome, Edge and Firefox, I am guessing that this is a code problem but can't find out what that would be.

Please help. Geo


Solution

  • There is a miscalculation in the onMouseMove event handler:

    item.style.top = e.clientY + mouseOffset.y + "px";
    

    When you move the mouse while holding the "TODO" item, the top of the whole element, including its margin, is being placed on the vertical coordinate of the viewport (e.clientY) where you clicked and adjusted to the point in the element where you clicked (+ mouseOffset.y), so the element moves along with the cursor. But it is ignoring its margin. If you pay attention, when you click and move the item, it will move down slightly. Those are 10 pixels of margin. When you click on the top, the element will be placed slightly down the cursor, the cursor will lose it, and it gets bugged. To fix, you have to substract the margin in the calculation.

    item.style.top = e.clientY - 10 + mouseOffset.y + "px";