1

I have created a little application where there is a dragzone and within it two

elements. I should have possibility to drag and drop these two paragraphs within this area. Code below works pretty well, but when i drop one element at the other element or at the edge of the dropzone or sometimes randomly this element move to the top left corner instead of right place. This is really annoying! Is there a way to go around this issue? Or is there a better way to write this app?

var section = document.querySelector("#dragzone");
  var currentLabel
  
  function moveStart(e) {
   e.dataTransfer.setData('text/plain', null);
   myX = e.offsetX === undefined ? e.layerX : e.offsetX;
   myY = e.offsetY === undefined ? e.layerY : e.offsetY;
   currentLabel = e.target;
  }

  function moveDragOver(e) {
   e.preventDefault();
   e.dataTransfer.dropEffect = "move";
  }

  function moveDrop(e) {
   e.preventDefault();
   currentLabel.style.left = e.offsetX - myX + 'px';
   currentLabel.style.top = e.offsetY - myY - 10 + 'px';
  }
  
  section.addEventListener('dragstart', moveStart, false);
  section.addEventListener('dragover', moveDragOver, false);
  section.addEventListener('drop', moveDrop, false);
#dragzone {
   position: relative;
   width: 300px;
   height: 300px;
   border: 2px solid black;
  }
  p {
   position: absolute;
   top: 20px;
   left: 20px;
  }
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>My site</title>
  
</head>

<body>
 <div id="dragzone">
  <p draggable="true">DraggableElement1</p>
  <p draggable="true">DraggableElement2</p>
 </div>
</body>
</html>

0 Answers0