HTML Drag

HTML Tutorial

HTML Forms

HTML Graphics

HTML Media

HTML API

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:

				
					<style>
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

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

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<p>Drag the image into the rectangle:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<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) {

 ev.dataTransfer.setData(“text”, ev.target.id);

}

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:

event.preventDefault()

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) {

  ev.preventDefault();

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

  ev.target.appendChild(document.getElementById(data));

}

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.