The simplest drag and drop feature with html and JavaScript - 16 lines
Rajesh Royal
Posted on February 5, 2022
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>
CodeSandbox URL: https://codesandbox.io/s/drag-and-drop-vky2h?file=/index.html
💖 💪 🙅 🚩
Rajesh Royal
Posted on February 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.