HTML Drag and Drop


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.


🔹 How Drag and Drop Works

To make an element draggable, set:

draggable="true"

The 3 Basic Steps:

  1. Drag Start → Fires when you begin dragging

  2. Drag Over → Fires when an item is dragged over a valid target

  3. Drop → Fires when the item is dropped


💻 Example: Simple Drag and Drop

<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>

🔹 Drag and Drop Events

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

Practice Questions

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.


Go Back Top