What Is HTML Drag and Drop API

In HTML Drag , any component can be moved.

Drag and Drop

Intuitive is an exceptionally normal element. It is the point at which you “snatch” an article and drag it to an alternate area.

Browser Support

The numbers in the table determine the principal program form that completely upholds Drag and Drop.

HTML Drag and Drop
HTML Drag and Drop

HTML Drag and Drop Example

The model underneath is a straightforward simplified model:

Example

<!DOCTYPE HTML>
<html>
<head>
<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>

<div id=”div1″ ondrop=”drop(event)” ondragover=”allowDrop(event)”></div>

<img id=”drag1″ src=”img_logo.gif” draggable=”true” ondragstart=”drag(event)” width=”336″ height=”69″>

</body>
</html>

It may appear to be convoluted, yet gives up through every one of the various pieces of a simplified occasion.

Make an Element Draggable

As a matter of first importance: To make a component draggable, set the draggable characteristic to valid:

What to Drag – ondragstart and setData()

Then, at that point, indicate what ought to happen when the component is hauled.

In the model over, the ondragstart characteristic calls a capacity, drag(event), that determines what information to be hauled.

The dataTransfer.setData() strategy sets the information type and the worth of the hauled information:

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

For this situation, the information type is “text” and the worth is the id of the draggable component (“drag1”).

Where to Drop – ondragover

The ondragover occasion indicates where the hauled information can be dropped.

Of course, information/components can’t be dropped in different components. To permit a drop, we should forestall the default treatment of the component.

This is finished by calling the event.preventDefault() technique for the ondragover occasion:

Do the Drop – ondrop

At the point when the hauled information is dropped, a drop occasion happens.

In the model over, the ondrop characteristic calls a capacity, drop(event): function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData(“text”);
  ev.target.appendChild(document.getElementById(data));
}

Code explained:

  • Call preventDefault() to forestall the program default treatment of the information (default is open as connection on drop)
  • Get the hauled information with the dataTransfer.getData() strategy. This strategy will return any information that was set to a similar kind in the setData() technique
  • The hauled information is the id of the hauled component (“drag1”)
  • Annex the hauled component into the drop component