HTML Drag and Drop

The Drag and Drop API enables users to drag elements and drop them into different locations on a web page. It is widely used for interactive interfaces and content reordering.

On this page

HTML Drag and Drop API

The HTML Drag and Drop API allows elements to be dragged and dropped using the mouse.

This feature is commonly used to move items between containers or rearrange content on a page.

What Is Drag and Drop?

Drag and drop means selecting an element, dragging it to a new location, and releasing it there.

The Drag and Drop API is supported by all modern browsers.

Basic Drag and Drop Example

The example below demonstrates a simple drag-and-drop interaction.

 function dragstartHandler(ev) {   ev.dataTransfer.setData("text", ev.target.id); }  function dragoverHandler(ev) {   ev.preventDefault(); }  function dropHandler(ev) {   ev.preventDefault();   const data = ev.dataTransfer.getData("text");   ev.target.appendChild(document.getElementById(data)); } 

Make an Element Draggable

To make an element draggable, set the draggable attribute to true.

 <img id="img1" draggable="true"> 
 <p id="p1" draggable="true">Draggable text</p> 

Handle the Drag Start

The ondragstart event defines what data is being dragged.

The dataTransfer.setData() method stores the dragged data.

 function dragstartHandler(ev) {   ev.dataTransfer.setData("text", ev.target.id); } 

In this example, the dragged data is the element’s id.

Allow Dropping

By default, elements do not allow drops.

The ondragover event must cancel the default behavior to enable dropping.

 function dragoverHandler(ev) {   ev.preventDefault(); } 

Handle the Drop

The ondrop event runs when the dragged element is released.

 function dropHandler(ev) {   ev.preventDefault();   const data = ev.dataTransfer.getData("text");   ev.target.appendChild(document.getElementById(data)); } 

How the Drop Logic Works

  • Prevents the browser’s default drop behavior
  • Retrieves the dragged element’s ID
  • Appends the dragged element to the drop target

Dragging Different Elements

The same logic works for different HTML elements.

Drag an <h1> Element

 <h1 id="h1" draggable="true"     ondragstart="dragstartHandler(event)">   Drag me </h1> 

Drag an <a> Element

 <a id="link1" href="#" draggable="true"    ondragstart="dragstartHandler(event)">   Draggable link </a> 

Common Use Cases

  • Reordering lists
  • Moving items between containers
  • Drag-and-drop file uploads
  • Interactive user interfaces

The Drag and Drop API provides a flexible way to build intuitive, interactive web experiences.

HTML Drag and Drop Examples (6)