Main Page

dataTransfer object

In this example, all the dragged item events fire, but no drop target event fires when you drag the text
over the red
<div/>
. In order to turn the
<div/>
into a valid drop target, you must override the default
behavior of
dragenter
and
dragover
. Because this is IE-specific, you can just set the
oEvent.returnValue
attribute to
false
:
<html>
<head>
<title>System Drag And Drop Example</title>
<script type=”text/javascript”>
function handleDragDropEvent(oEvent) {
var oTextbox = document.getElementById(“txt1”);
oTextbox.value += oEvent.type + “\n”;
switch(oEvent.type) {
case “dragover”:
case “dragenter”:
oEvent.returnValue = false;
}
}
</script>
</head>
<body>
<p>Try dragging the text from the textbox to the red square.
Drop target events fire now.</p>
<form>
<p><input type=”text” value=”drag this text”
ondragstart=”handleDragDropEvent(event)”
ondrag=”handleDragDropEvent(event)”
ondragend=”handleDragDropEvent(event)” />
<div style=”background-color: red; height: 100px; width: 100px”
ondragenter=”handleDragDropEvent(event)”
ondragover=”handleDragDropEvent(event)”
ondragleave=”handleDragDropEvent(event)”
ondrop=”handleDragDropEvent(event)”></div></p>
<p><textarea rows=”10” cols=”25” readonly=”readonly”
id=”txt1”></textarea></p>
</form>
</body>
</html>
In this example, when you drag the text over the red
<div/>
, the cursor changes to a pointer with a
plus sign next to it, indicating that this is a valid drop target. By default, the
dragenter
and
dragover
events for the
<div/>
don’t allow dropping, so if you prevent the default behavior you allow the
<div/>
to become a drop target. After
dragenter
and
dragover
are fired,
dragleave
and
drop
are
also enabled.
The dataTransfer object
Simply dragging and dropping isn’t of any use unless data is actually being affected. To aid in the trans-
mission of data via drag and drop, Internet Explorer 5.0 introduced the
dataTransfer
object, which
exists as a property of
event
and is used to transfer string data from the dragged item to the drop target
(the
dataTransfer
object is still used in IE 6.0).
393
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:40 AM Page 393


JavaScript EditorFree JavaScript Editor     Ajax Editor


©