HTML Drag and Drop Lecture
Welcome to this tutorial on HTML5's Drag and Drop API. This API offers a straightforward way to implement drag-and-drop features in web applications. By the end of this lecture, you'll have a solid understanding of how to incorporate this user-friendly interaction into your websites or web apps.
What Is Drag and Drop?
Drag and drop is a graphical user interface design pattern that allows users to click and hold on an item, move it to another location, and release it. This action is especially useful for operations like reordering lists, moving objects, or copying files. HTML5 introduces native drag and drop functionality, so you no longer need to rely solely on JavaScript libraries for this feature.
Getting Started: Basic Attributes
To start with, you'll need two essential HTML attributes: draggable
and ondragstart
.
draggable
: Determines whether an element can be dragged or not. Set it totrue
to make an element draggable.ondragstart
: This attribute holds the JavaScript function that will be called when the drag operation begins.
Example:
<div id="dragItem" draggable="true" ondragstart="drag(event)">Drag me!</div>
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
The Drop Zone: ondragover and ondrop
To complete a drag and drop operation, we need a 'drop zone'. For this, we use two other attributes:
ondragover
: Specifies a JavaScript function to be called when an element is dragged over the drop zone.ondrop
: Specifies a JavaScript function to be called when an element is dropped into the drop zone.
Example:
<div id="dropZone" ondragover="allowDrop(event)" ondrop="drop(event)">Drop here</div>
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
Full Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Drag and Drop Example</title>
<script>
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="dragItem" draggable="true" ondragstart="drag(event)">Drag me!</div>
<div id="dropZone" ondragover="allowDrop(event)" ondrop="drop(event)">Drop here</div>
</body>
</html>
Advanced Topics
While the basics can be covered with just the HTML5 attributes, you can create more complex drag-and-drop interfaces using JavaScript's Drag and Drop API, like handling multiple items, changing the appearance of the drag item, or adding animation.
Conclusion
The HTML5 Drag and Drop API allows you to add interactive and user-friendly features to your web applications with relative ease. It can be used for a variety of purposes, ranging from simple list reordering to complex file manipulations.