Drag and Drop Feature is one of the most interactive features in a website and in this blog, we will explore how to create a simple drag-and-drop feature using JavaScript, HTML, and CSS. Let’s see this effect:

Explanation of the Code
- The HTML defines the basic structure with a heading, a container div, and two boxes labeled “left” and “right.” Each box contains draggable items styled as red boxes with white text.
- CSS designs the layout, adds dashed borders to the boxes, and styles the draggable items. JavaScript handles the drag and drop feature functionality by adding event listeners for dragstart, dragover, and drop events.
- When a user drags an item, the target box highlights its readiness to accept the item. Upon dropping, the item is appended to the target box.
GitHub Source Code for Drag and Drop Feature: Link
<strong><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag & DROP</title>
<style>
*{
padding: 10px;
margin: 0;
box-sizing: border-box;
}
#container{
margin-top: 40px;
display: flex;
}
h1{
text-align: center;
}
.Hi{
margin-right: 5em;
border:dashed;
height: 200px;
width: 250px;
display: flex;
flex-direction: column;
justify-content: center;
}
.list{
color: whitesmoke;
margin-top: 5px;
width:200px;
height: 50px;
background-color:red;
}
</style>
</head>
<body>
<div>
<h1>Drag & Drop</h1>
<div id="container">
<div class="Hi" id="left">
<div draggable="true" class="list">Box</div>
<div draggable="true" class="list">Box</div>
</div>
<div class="Hi" id="right" >
<div draggable="true" class="list">Box</div>
<div draggable="true" class="list">Box</div>
</div>
</div>
</div>
<script>
const lists=document.getElementsByClassName("list");
const leftBox=document.getElementById("left");
const rightBox=document.getElementById("right");
for(list of lists){
list.addEventListener('dragstart',(e)=>{
let selectedElement=e.target;
rightBox.addEventListener("dragover",(e)=>{
e.preventDefault();
})
rightBox.addEventListener("drop",(e)=>{
rightBox.appendChild(selectedElement);
selectedElement=null;
})
leftBox.addEventListener("dragover",(e)=>{
e.preventDefault();
})
leftBox.addEventListener("drop",(e)=>{
leftBox.appendChild(selectedElement);
selectedElement=null;
})
})
}
</script>
</body>
</html></strong>
Conclusion
Drag an item from one box to another. While hovering over the target box, the dragover event ensures the box is ready to accept the drop. Once dropped, the item moves to the new box. This interaction is seamless and intuitive, creating an engaging user experience.
For more such coding projects in JavaScript, C++ and Python: Link
Thank you so much for visiting our website, CodeHelping.