HTML 5 Drag and Drop

Drag and drop (Drag and drop) are part of the HTML5 standard.

Drag and drop

Drag and drop is a common feature, that is, grab an object and drag it to another location.

In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.

HTML5 drag and drop example

The following example is a simple drag and drop example:

Example

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"> 
<title>Novice Tutorial</title>
<style type="text/css">
#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 HACKERTHINK.COM picture to the rectangular box:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="/images/logo.png" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

Set the element to be draggable

First, in order to make the element draggable, set the draggable attribute to true:

<img draggable="true">

What to drag-ondragstart and setData()

Then, specify what happens when the element is dragged.

In the above example, the ondragstart attribute calls a function, drag(event), which specifies the data to be dragged.

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

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

Text is a DOMString representing the type of drag data to be added to the drag object. The value is the id of the draggable element (“drag1”).

Where to put-ondragover

The ondragover event specifies where to drop the dragged data.

By default, data/elements cannot be placed in other elements. If you need to set the allowable placement, we must prevent the default handling of the element.

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

event.preventDefault()

Placement-ondrop

When the dragged data is dropped, the drop event will occur.

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

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

Code explanation:

  • Call preventDefault() to avoid the browser’s default processing of data (the default behavior of the drop event is to open it as a link)
  • Get the dragged data through the dataTransfer.getData(“Text”) method. This method will return any data set to the same type in the setData() method.
  • The dragged data is the id of the dragged element (“drag1”)
  • Append the dragged element to the dropped element (target element)