The HTML Drag and Drop API is a set of events and interfaces that allow developers to enable drag and drop functionality in web applications. With this API, users can click and drag elements on a web page and drop them onto a target location.
To use the HTML Drag and Drop API, the following events can be used:
- ondragstart: This event is fired when the user starts to drag an element.
- ondrag: This event is fired continuously as the user is dragging an element.
- ondragend: This event is fired when the user finishes dragging an element.
- ondragenter: This event is fired when a draggable element enters a drop target.
- ondragover: This event is fired continuously as a draggable element is being dragged over a drop target.
- ondragleave: This event is fired when a draggable element leaves a drop target.
- ondrop: This event is fired when a draggable element is dropped onto a drop target.
To enable drag and drop functionality, the draggable attribute is added to the HTML element that can be dragged, and the ondragstart event is defined. The ondragover event is then used to allow the drop target to accept the draggable element, and the ondrop event is used to handle the drop action.
Here’s an example of how to use the HTML Drag and Drop API:
<!DOCTYPE html>
<html>
<head>
<title>HTML Drag and Drop API</title>
<style>
#drag {
width: 100px;
height: 100px;
background-color: red;
}
#drop {
width: 200px;
height: 200px;
background-color: green;
margin-top: 20px;
}
</style>
<script>
function dragStart(event) {
event.dataTransfer.setData("text/plain", event.target.id);
}
function dragOver(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text/plain");
event.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="drag" draggable="true" ondragstart="dragStart(event)"></div>
<div id="drop" ondragover="dragOver(event)" ondrop="drop(event)"></div>
</body>
</html>
In this example, the div element with the id “drag” can be dragged and dropped onto the div element with the id “drop”. The dragStart function is called when the drag operation starts and sets the data type and value to be transferred. The dragOver function is called continuously as the draggable element is being dragged over the drop target and prevents the default action of not allowing a drop. Finally, the drop function is called when the draggable element is dropped onto the drop target and appends the draggable element to the drop target.