-
Hajipur, Bihar, 844101
The HTML Drag and Drop API lets you make HTML elements draggable and allows users to move them between different locations on a web page. It’s often used for:
File uploads
Rearranging items
Visual editors
This feature uses built-in JavaScript events to control drag behavior.
To make an element draggable, set:
draggable="true"
Drag Start → Fires when you begin dragging
Drag Over → Fires when an item is dragged over a valid target
Drop → Fires when the item is dropped
<style>
#drag1, #box {
width: 150px; height: 100px; padding: 10px;
border: 1px solid black; margin: 10px;
}
#box {
background-color: #f0f0f0;
}
</style>
<p>Drag the element into the box:</p>
<div id="drag1" draggable="true" ondragstart="drag(event)">Drag me</div>
<div id="box" ondrop="drop(event)" ondragover="allowDrop(event)">Drop here</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
const data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
Event | Triggered When... |
---|---|
dragstart |
User starts dragging an element |
drag |
Fires continuously during drag |
dragenter |
Element enters a valid drop target |
dragover |
Element is over a valid drop target |
dragleave |
Element leaves a valid drop target |
drop |
Element is dropped |
dragend |
Drag operation is completed |
Q1. Make a <div>
draggable using draggable="true"
.
Q2. Create a drop zone <div>
that accepts dragged content.
Q3. Use ondragstart
to store data in dataTransfer
.
Q4. Prevent default behavior using ondragover
.
Q5. Append the dragged element to the new parent on drop.
Q6. Add CSS styling to highlight the drop area on dragenter
.
Q7. Use dragend
to reset the dragged element’s style.
Q8. Make a list of images that can be dragged into a gallery area.
Q9. Create two containers to drag items between them.
Q10. Allow only specific elements to be dropped using dataTransfer
checks.
Q1: Which attribute enables an HTML element to be draggable?
Q2: Which event occurs when you start dragging an element?
Q3: What is the purpose of ev.preventDefault() in ondragover?
Q4: Which method is used to set data for dragging?
Q5: Which method is used to get data during drop?
Q6: Which event fires when the dragged item is dropped?
Q7: What does ondragover do?
Q8: Can any HTML element be made draggable?
Q9: What’s the role of ondrop event?
Q10: Which object provides drag and drop data transfer?