HTML Tutorial

HTML Forms

HTML Graphics

HTML Media


HTML Drag/Drop

  • In HTML, any element can be dragged and dropped.

    Drag and Drop

    Drag and drop is referred to as a process of grabbing  object and dragging it to a different location.

    HTML Drag and Drop Example

    Below is a simple example of drag and drop:

#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
function allowDrop(ev) {

function drag(ev) {

function drop(ev) {
  var data = ev.dataTransfer.getData("text");;
<p>Drag the image into the rectangle:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img decoding="async" id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">


Drag the image into the rectangle:

Make an Element Draggable

Set the draggable attribute to true so as to make an element draggable:


What to Drag – ondragstart and setData()

Mention the step what should once the element is dragged.

In the above example, the ondragstart attribute calls a function, drag(event), that is used to specify what data should to be dragged.

The dataTransfer.setData() method defines the data type and the value of the data that is to be dragged:

function drag(ev) {



In this case, the data type is “text” and the value is the id of the draggable element (“drag1”).

Where to Drop – ondragover

The ondragover event defines where the dragged data must be dropped.

Data /elements cannot be dropped in other elements by default. To enable a drop, you need to prevent the default handling of the element.

This is done by calling the event.preventDefault() method for the ondragover event:


Do the Drop – ondrop

A drop event occurs as soon as the dragged data is dropped.

In the above example, the ondrop attribute calls a function, drop(event):

function drop(ev) {


  var data = ev.dataTransfer.getData(“text”);;


Code explained:

  • Call preventDefault() avoids the browser default handling of the data.
  • Get the dragged data with the dataTransfer.getData() method. This method returns any data set to the same type in the setData() method.
  • The dragged data is defined as the id of the dragged element (“drag1”).
  • The dragged element is appended into the drop element.

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/ on line 5420

Notice: ob_end_flush(): failed to send buffer of zlib output compression (1) in /home/u212091429/domains/ on line 5420