We saw the main principles of HTML5 drag and drop in the previous sections. There are other interesting uses that differ in the way we copy and paste things to/from the clipboard. The clipboard is accessed through the dataTransfer property of the different events:
event.dataTransfer.setData("Fruit", event.target.dataset.value);
...
var data = event.dataTransfer.getData("Fruit");
Normally, to make an element draggable, you must add the draggable=true attribute. <img> elements are an exception: they are draggable by default! The next example shows how to drag and drop an image from one location in the document to another.
Try this example (adapted from braincracking.org (in French)) in your browser below or play with it at CodePen:
Code from the example:
<html lang="en">
<head>
<style>
.box {
border: silver solid;
width: 256px;
height: 128px;
margin: 10px;
padding: 5px;
float: left;
}
</style>
<script>
function drag(target, evt) {
evt.dataTransfer.setData("Text", target.id);
}
function drop(target, evt) {
var id = evt.dataTransfer.getData("Text");
target.appendChild(document.getElementById(id));
// prevent default behavior
evt.preventDefault();
}
</script>
</head>
<body>
Drag and drop browser images in a zone:<br/>
<img src="https://mainline.i3s.unice.fr/mooc/ABiBCwZ.png" id="cr"
ondragstart="drag(this, event)" alt="Logo Chrome">
<img src="https://mainline.i3s.unice.fr/mooc/n7xo93U.png" id="ff"
ondragstart="drag(this, event)" alt="Logo Firefox">
<img src="https://mainline.i3s.unice.fr/mooc/ugUmuGQ.png" id="ie"
ondragstart="drag(this, event)" alt="Logo IE">
<img src="https://mainline.i3s.unice.fr/mooc/jfrNErz.png" id="op"
ondragstart="drag(this, event)" alt="Logo Opera">
<img src="https://mainline.i3s.unice.fr/mooc/gDJCG0l.png" id="sf"
ondragstart="drag(this, event)" alt="Logo Safari"><br/>
<div class="box" ondragover="return false" ondrop="drop(this, event)">
<p>Good web browsers</p>
</div>
<div class="box" ondragover="return false" ondrop="drop(this, event)">
<p>Bad web browsers</p>
</div>
</body>
</html>
The trick here is to only work on the DOM directly. We used a variant of the event handler proposed by the DOM API. This time, we used handlers with two parameters (the first parameter, target, is the element that triggered the event, and the second parameter is the event itself). In the dragstart handler we copy just the id of the element in the DOM (line 15).
In the drop handler, we just move the element from one part of the DOM tree to another (under the <div> defined at line 38, that is the drop zone). This occurs at line 18 (get back the id from the clipboard), and line 19 (make it a child of the div. Consequently, it is no longer a child of the <body>, and indeed we have "moved" one <img> from its initial position to another location in the page).