HTML5 – Drag and drop
Drag and drop is a user interface feature that allows users to move elements from one place to another by dragging them. HTML5 introduced the draggable
attribute, which allows elements to be dragged and dropped.
To make an element draggable, you can set the draggable
attribute to true
:
<div draggable="true">Drag me!</div>
To handle the drag and drop events, you can use the ondragstart
, ondrag
, and ondragend
event handlers:
<div draggable="true" ondragstart="onDragStart(event)" ondrag="onDrag(event)" ondragend="onDragEnd(event)">Drag me!</div>
In this example, the ondragstart
event handler is called when the drag operation starts, the ondrag
event handler is called while the element is being dragged, and the ondragend
event handler is called when the drag operation ends.
You can also use the ondragover
and ondrop
event handlers to handle the drop operation:
<div id="drop-zone" ondragover="onDragOver(event)" ondrop="onDrop(event)">Drop here</div>
In this example, the ondragover
event handler is called when an element is dragged over the drop-zone
element, and the ondrop
event handler is called when the element is dropped into the drop-zone
element.
Here is an example of how to use the drag and drop event handlers to move elements:
<style>
.draggable {
cursor: move;
}
</style>
<div id="drag-source" class="draggable" draggable="true" ondragstart="onDragStart(event)">
Drag me!
</div>
<div id="drop-target" ondragover="onDragOver(event)" ondrop="onDrop(event)">
Drop here
</div>
<script>
function onDragStart(event) {
event.dataTransfer.setData('text', event.target.id);
}
function onDragOver(event) {
event.preventDefault();
}
function onDrop(event) {
var sourceId = event.dataTransfer.getData('text');
var source = document.getElementById(sourceId);
var target = event.target;
target.appendChild(source);
}
</script>
In this example, the onDragStart
function is called when the drag-source
element is dragged. The function sets the data to be transferred to the text
data type and the id
of the element. The onDragOver
function is called when the drag-source
element is dragged over the drop-target
element, and the onDrop
function is called when the drag-source
element is dropped into the drop-target
element.
The onDrop
function gets the id
of the drag-source
element from the data transferred using the getData
method, gets a reference to the drag-source
element using the getElementById
method, and appends the drag-source
element to the drop-target
element using the appendChild
method. This moves the drag-source
element to the drop-target
element when the drag-source
element is dropped into the drop-target
element.