Java Reference
In-Depth Information
But also remember that Example 19 doesn't completely work in Firefox. Although it is frustrating
that JavaScript developers have to cope with inconsistent implementations, Firefox's drag‐and‐drop
implementation, whether it's right or wrong, does make some sense in this regard. As we try to drag
the red box, we haven't told the browser what we're transferring.
transferring data
When you think about it, a drag‐and‐drop operation is the transference of data. For example, when
you drag a file on your filesystem from one folder to another, you are transferring the data (the file)
between the two folder locations. When dragging text from one application to another, you are
transferring the textual data between the two applications.
Drag and drop in the browser follows a similar concept. When starting a drag, you need to tell the
browser what you plan to transfer, and when you drop the object, you need to specify how that data
transfers from the source to the target.
The drag‐and‐drop specification defines a
DataTransfer
object that is used to hold the data that
is being dragged during a drag‐and‐drop operation. You access this object with the
Event
object's
dataTransfer
property. You set data with the
DataTransfer
object's
setData()
method in the
dragstart
event handler, and you read that data in the
drop
event handler with the
getData()
method.
To make Example 19 work in Firefox, you need to handle the
dragstart
event and use the
DataTransfer
object's
setData()
method. The following adds the necessary code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10: Example 20</title>
<style>
.box {
width: 100px;
height: 100px;
}
.red {
background-color: red;
}
.drop-zone {
width: 300px;
padding: 20px;
border: 2px dashed #000;
}
</style>
</head>
<body>
<div draggable="true" class="box red"></div>
<div id="dropZone" class="drop-zone">Drop Zone!</div>
<div id="dropStatus"></div>
<script>