Back to roadmaps html Course
Table of Contents (31 guides)

HTML5 Drag and Drop API: Creating Interactive UI

HTML5 introduces native drag-and-drop (DnD) support, allowing you to build features like file upload boxes, draggable cards, or kanban boards without heavy external libraries. Let's study how this API works.


1. Making an Element Draggable

To make any HTML element draggable, add the draggable="true" attribute to it.

<!-- This box can now be dragged around the page -->
<div id="drag-item" draggable="true">Drag me!</div>

2. Understanding the Event Cycle

Drag-and-drop interactions rely on a series of JavaScript events triggered on the draggable item and the drop target.

Event Name Trigger Location Description
dragstart Draggable Item Fires when the user starts dragging the item
dragover Drop Zone Fires continuously while the item is held over the drop zone
drop Drop Zone Fires when the user releases the item inside the drop zone

3. Practical Code Implementation

Here is a simple example showing how to drag a box and drop it into another container:

The HTML Structure:

<!-- Drop Zones -->
<div id="left-zone" class="zone">
  <div id="drag-box" draggable="true">Draggable Content</div>
</div>

<div id="right-zone" class="zone">
  <!-- Dropped elements will go here -->
</div>

The JavaScript Logic:

const dragBox = document.getElementById('drag-box');
const dropZones = document.querySelectorAll('.zone');

// 1. Store the ID of the dragged element on dragstart
dragBox.addEventListener('dragstart', (event) => {
  event.dataTransfer.setData('text/plain', event.target.id);
});

// 2. Allow dropping by preventing default dragover behavior
dropZones.forEach(zone => {
  zone.addEventListener('dragover', (event) => {
    event.preventDefault(); // Crucial! Browsers disable dropping by default
  });

  // 3. Handle the drop event
  zone.addEventListener('drop', (event) => {
    event.preventDefault();
    
    // Retrieve the dragged item ID and append it to the drop zone
    const itemId = event.dataTransfer.getData('text/plain');
    const draggedItem = document.getElementById(itemId);
    
    event.target.appendChild(draggedItem);
  });
});

4. Customizing the Drag Image

You can customize the ghost image that follows the user's cursor during the drag event using event.dataTransfer.setDragImage().

dragBox.addEventListener('dragstart', (event) => {
  const img = new Image();
  img.src = '/ghost-icon.png';
  event.dataTransfer.setDragImage(img, 10, 10);
});

5. Summary

  • Always call event.preventDefault() on the dragover event, otherwise, the drop event will never fire.
  • Use dataTransfer to pass string data between your drag event and your drop event handlers.
Published on