HTML 5 Drag and drop
Drag-and-drop (Drag and Drop) is part of the HTML5 standard.
Drag and drop
Drag-and-drop is a common feature that grabs an object and then drags it to another location.
In HTML5, drag-and-drop is part of the standard, and any element can be dragged and dropped.
Browser support
Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5 support drag and drop.
Note: drag-and-drop is not supported in Safari 5.1.2.
HTML5 drag and Drop instances
The following example is a simple drag-and-drop instance:
Instance
<! DOCTYPE html>
<script type= "Text/javascript" >
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>
<body>
<div id= "Div1" ondrop= "Drop (event)"
Ondragover= "AllowDrop (event)" ></div>
ondragstart= "Drag (Event)" Width= "336" height= ""/>
</body>
Try it yourself.
It may seem a little complicated, but we can study the different parts of the drag-and-drop event separately.
Set elements to be dragged and dropped
First, to make an element draggable, set the Draggable property to True:
What to drag-ondragstart and SetData ()
Then, specify what happens when the element is dragged.
In the example above, the Ondragstart property invokes 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);
}
In this example, the data type is "Text" and the value is the ID of the draggable element ("Drag1").
Where to put it-ondragover
The OnDragOver event specifies where to place the dragged data.
By default, data/elements cannot be placed in other elements. If you need to set allow placement, we must block the default handling of elements.
This is done by invoking the event for OnDragOver events. Preventdefault () Method:
Event.preventdefault ()
To place-OnDrop
The drop event occurs when the dragged data is dropped.
In the example above, the OnDrop property invokes 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 browser default handling of data (the default behavior of the drop event is to open as a link)
- The dragged data is obtained by means of the Datatransfer.getdata ("Text") method. The method returns any data that is set to the same type in the SetData () method.
- The dragged data is the ID of the dragged element ("Drag1")
- Appends the dragged element to the placement element (the target element)
More examples
Drag and drop pictures back and forth
How to drag and drop an image between two <div> elements.
H5 Drag and drop