Skip to main content

HTML Drag and Drop API

By SamK
0
0 recommends
Topic(s)

In HTML, any element can be made draggable.

Drag and drop is a widely used feature that allows you to "grab" an object and move it to a different location.

HTML Drag and Drop Example

The following is a basic drag and drop example:

<!DOCTYPE HTML>
<html>
<head>
<script>
function dropFn(e) {
 e.preventDefault();
}
function drag(e) {
 e.dataTransfer.setData("text", e.target.id);
}
function drop(e) {
 e.preventDefault();
 var data = e.dataTransfer.getData("text");
 e.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="ndiv" ondrop="drop(event)" ondragover="dropFn(event)"></div>
<img id="idrag" src="image.png" draggable="true" ondragstart="drag(event)" width="300" height="200">
</body>
</html> 

Drag and Drop Demo

The above preview shows the <div> and <img> elements before drag and drop, and the below preview shows these elements after drag and drop.

DRag and Drop Demo

How it Works:

Make an Element Draggable

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

<img draggable="true">

What to Drag - ondragstart and setData()

Then, specify what should happen when the element is dragged.

In the example above, the ondragstart attribute calls a function drag(e), that specifies what data to be dragged.

The dataTransfer.setData() method sets the data type and the value of the dragged data:

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

In this case, the data type is "text," and the value is the ID of the draggable element ("idrag").

Where to Drop - ondragover

The ondragover event determines where the dragged data can be dropped.

By default, data/elements cannot be dropped in other elements. To allow a drop, we must prevent the default behavior.

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

 e.preventDefault()

Do the Drop - ondrop

When the dragged data is dropped, a drop event occurs.

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

function drop(e) {
  e.preventDefault();
  var data = e.dataTransfer.getData("text");
  e.target.appendChild(document.getElementById(data));
}

Code explained:

  • Call preventDefault() to stop the browser's default handling of the data (which is to open as a link on drop).
  • Use the dataTransfer.getData() method to retrieve the dragged data. This method returns any data set to the same type in the setData() method.
  • The dragged data is the ID of the dragged element ("idrag").
  • Append the dragged element to the drop target.

This was a simple HTML Drag and Drop tutorial. You'll learn more about this in our next tutorials.

Please check below options for the links to our previous or next tutorial.

Questions & Answers