Using HTML Drag and Drop API to move container element smoothly

Viewed 27

Trying to use the HTML Drag and Drop API to simply allow a user to reposition a container element while dragging from a drag handle.

I have the element moving and repositioning using drag and dragend but it's looking a bit glitchy - the element snaps back to it's previous position before re-rendering in its dropped position.

I know there's a simple(r) solution using mousedown but hoping to use the draggable API as my app has global mousedown listeners for another use case.

It seems just super poor performance, but probably I'm doing something totally wrong with the API here!

Thanks so much!

let dragHandle = document.getElementById("drag-handle");

let container = document.getElementById("drag-container");


dragHandle.addEventListener("drag", (event) => {
  container.style.left = event.screenX + "px";
  container.style.top = event.screenY + "px";
});

dragHandle.addEventListener("dragend", (event) => {
  container.style.left = event.clientX + "px";
  container.style.top = event.clientY + "px";
});
.drag-handle {
  cursor: grab;
}
.container {
  position: absolute;
  top: 5px;
  left: 5px;
}
<div class="container" id="drag-container">
  <div  
       class="drag-handle" 
       id="drag-handle"
       draggable="true">drag me</div>
<div>

0 Answers
Related