learn2kode.in

JavaScript Drag & Drop API

JavaScript Drag & Drop API – Beginner-Friendly Guide

The JavaScript Drag & Drop API allows you to make web elements draggable and droppable using simple JavaScript and HTML. It is widely used in modern web applications to improve user interaction and user experience.
Examples you see every day include:
In this tutorial, you’ll learn how the JavaScript Drag and Drop API works, key events, and a simple example.
What Is the Drag & Drop API?
The Drag & Drop API is part of HTML5 and JavaScript Web APIs that enables users to click, drag, and drop elements within a web page.
It works using:
This API is supported by all modern browsers.

Making an Element Draggable

To enable drag functionality, simply add the draggable attribute:
<div id="box" draggable="true">Drag me</div>
This tells the browser that the element can be dragged.
Important Drag & Drop Events
JavaScript listens to specific events during the drag process.
Drag Events:
Drop Events:
Basic JavaScript Drag & Drop Example
<div id="dragItem" draggable="true">Drag me</div>
<div id="dropZone">Drop here</div>

<script>
const dragItem = document.getElementById("dragItem");
const dropZone = document.getElementById("dropZone");

dragItem.addEventListener("dragstart", (e) => {
  e.dataTransfer.setData("text/plain", dragItem.id);
});

dropZone.addEventListener("dragover", (e) => {
  e.preventDefault(); // Required to allow drop
});

dropZone.addEventListener("drop", (e) => {
  const id = e.dataTransfer.getData("text/plain");
  dropZone.appendChild(document.getElementById(id));
});
</script>
What’s Happening Here?
dataTransfer Object Explained
The dataTransfer object carries data during drag operations.
Common methods:
This allows flexible data handling while dragging elements.

Use Cases of Drag & Drop API

The JavaScript Drag and Drop API is commonly used for:
This makes it a powerful feature for modern front-end development.
Drag & Drop API vs Mouse Events
Feature Drag & Drop API Mouse Events
Built-in support Yes No
Mobile friendly Limited Better
Complexity Simple Complex
Best for UI interactions Custom logic

Best Practices

When Should You Use Drag & Drop?

Use the Drag & Drop API when:
For complex needs, libraries like SortableJS or Dragula may help.