↑
Main Page
Methods
Because it is a property of
event
, the
dataTransfer
object doesn’t exist except within the scope of an
event handler, specifically, an event handler for a drag-and-drop event. Within an event handler, you can
use the object’s properties and methods to work with your drag-and-drop functionality.
Methods
The
dataTransfer
object has two methods:
getData()
and
setData()
. As you might expect,
getData()
is capable of retrieving a value stored by
setData()
. Two types of data can be set: plain text
and URLs. The first argument for
setData()
, and the only argument of
getData()
, is a string indicat-
ing which type of data is being set, either
“text”
or
“URL”
. For example:
oEvent.dataTransfer.setData(“text”, “some text”);
var sData = oEvent.dataTransfer.getData(“text”);
oEvent.dataTransfer.setData(“URL”, “http://www.wrox.com/”);
var sURL = oEvent.dataTransfer.getData(“URL”);
It should be noted that two spaces can be used to store data: one for text and one for a URL. If you make
repeated calls to
setData()
, you are always overwriting the data stored in the space specified.
The data stored in the
dataTransfer
object is only available up until the
drop
event. If you do not
retrieve the data in the
ondrop
event handler, the
dataTransfer
object is destroyed and the data is lost.
When you drag text from a text box, the operating system calls
setData()
and stores the dragged text
in the
“text”
format. It is possible to retrieve this value when it is dropped on a target. Consider the fol-
lowing example:
<html>
<head>
<title>System Drag And Drop Example</title>
<script type=”text/javascript”>
function handleDragDropEvent(oEvent) {
switch(oEvent.type) {
case “dragover”:
case “dragenter”:
oEvent.returnValue = false;
break;
case “drop”:
alert(oEvent.dataTransfer.getData(“text”));
}
}
</script>
</head>
<body>
<p>Try dragging the text from the textbox to the red square.
It will show you the selected text when dropped.</p>
<p><input type=”text” value=”drag this text” />
<div style=”background-color: red; height: 100px; width: 100px”
ondragenter=”handleDragDropEvent(event)”
ondragover=”handleDragDropEvent(event)”
ondrop=”handleDragDropEvent(event)”></div></p>
</body>
</html>
394
Chapter 13
16_579088 ch13.qxd 3/28/05 11:40 AM Page 394
Free JavaScript Editor
Ajax Editor
©
→