Skip to main content

HTML Drag and Drop API

The HTML Drag and Drop API lets an element be dragged and dropped.


Drag and Drop

Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different place.


Browser Support

Drag and Drop is supported in all modern browsers (from Chrome 4, Edge 9, Firefox 3.5, Safari 6, and Opera 12).


HTML Drag and Drop API Example

Here is a simple drag-and-drop example: a draggable image and a target div.

Example

Dragging an image into a div.

Prompt
A drag-and-drop demo: a draggable image and a target div, using ondragstart/setData, ondragover/preventDefault, and ondrop to move the image into the div.
Output: complete HTML page

Make an Element Draggable

First, to make an element draggable, set its draggable attribute to true. This works on any element, such as an image or a paragraph.

Draggable image

An image made draggable.

index.html
<img id="img1" draggable="true">

Draggable paragraph

A paragraph made draggable.

index.html
<p id="p1" draggable="true">Draggable text</p>

What to Drag - ondragstart and setData()

Next, say what happens when the element is dragged. The element's ondragstart attribute calls a function (here dragstartHandler) that sets the data to be dragged. The dataTransfer.setData() method sets the data type and value; in the example the type is "text" and the value is the id of the dragged element.


Where to Drop - ondragover

The target element's ondragover attribute calls a function (here dragoverHandler) that says where the data can be dropped. By default, data cannot be dropped into other elements, so to allow a drop you must call preventDefault() on the ondragover event.


Do the Drop - ondrop

When the dragged data is dropped, a drop event fires. The target's ondrop attribute calls a function (here dropHandler) that: calls preventDefault() to stop the browser's default handling (which is to open the data as a link), gets the dragged data with dataTransfer.getData() (the id of the dragged element), and appends the dragged element into the drop target.


More Examples

The same handlers can drag other kinds of elements into a div, or move an image back and forth between two divs.

Drag an h1 into a div

Dragging a heading into a div.

Prompt
A drag-and-drop demo that drags an h1 heading (PromptCookbook) into a target div, using the same dragstart, dragover and drop handlers.
Output: complete HTML page

Drag a link into a div

Dragging a link into a div.

Prompt
A drag-and-drop demo that drags a link (a element to PromptCookbook.com) into a target div, using the same dragstart, dragover and drop handlers.
Output: complete HTML page

Drag back and forth between two divs

Moving an image between two divs.

Prompt
A drag-and-drop demo with two target divs where an image can be dragged back and forth between them, using shared dragstart, dragover and drop handlers.
Output: complete HTML page