HTML Drag and Drop API


Using Drag and Drop

Drag and drop is a widely used feature. It happens when you "grab" an object and drag it to a new location. Any element in HTML can be dragged and dropped Using this API.

Example

Preview

Make a Draggable Element

First and foremost: Set the draggable attribute to true to make an element draggable:

Syntax


What to Drag - ondragstart and setData are two options ()

Then, define what happens when the element is dragged. In the preceding example, the ondragstart attribute invokes a function, drag(event), which specifies the data to be dragged.

The dataTransfer.setData() method configures the dragged data's data type and value:

Syntax

 The data type in this case is "text," and the value is the id of the draggable element ("drag").


Dropping Points - ondragover

The ondragover event specifies the location where the dragged data can be dropped. Data/elements cannot be dropped into other elements by default. To allow a drop, we must prevent the element's default handling.

This is accomplished by invoking the ondragover event's event.preventDefault() method:

Syntax


Perform the Drop - ondrop

A drop event occurs when the dragged data is dropped. In the preceding example, the ondrop attribute invokes a function, drop(event):

Syntax

 Explanation of the code:

  • To prevent the browser's default handling of the data, use preventDefault() (default is open as link on drop).
  • The dataTransfer.getData() method is used to retrieve the dragged data. This method returns any data set to the same type in the setData() method.
  • The dragged data is the dragged element's id ("drag").
  • The dragged element is appended to the drop element.

FAQs

The 'drag' and 'dragover' events are fired as the mouse is moving over an element when a drag is occurring in HTML.

A drop event occurs when the dragged data is dropped, and you can specify what happens then using the ondrop attribute.

To specify what data can be dragged and dropped in HTML, you can use the setData() method to set the data type and value of the data being dragged.