DEV Community

Cover image for The simplest drag and drop feature with html and JavaScript - 16 lines
Rajesh Royal
Rajesh Royal

Posted on

The simplest drag and drop feature with html and JavaScript - 16 lines

The Code:

<!Doctype html>
<head>
<script>
const allowDrop = (e) => e.preventDefault();
const drag = (e) => e.dataTransfer.setData("text", e.target.id);
const drop = (e) => {
  var data = e.dataTransfer.getData("text");
  e.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body ondrop="drop(event)" ondragover="allowDrop(event)"
 style="height: 100vh; width: 100vw">

<div ondrop="drop(event)" ondragover="allowDrop(event)"
 style="width:150px; height:50px; padding: 10px; 
border:1px solid black"></div>

<p id="drag" draggable="true" ondragstart="drag(event)">
Drag me into box</p>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

CodeSandbox URL: https://codesandbox.io/s/drag-and-drop-vky2h?file=/index.html

Top comments (0)