Java Reference
In-Depth Information
targets[i].addEventListener("dragenter", handleDragEnterLeave);
targets[i].addEventListener("dragleave", handleDragEnterLeave);
}
</script>
</body>
</html>
Save this file as
ch12 _ example1.html
.
You need just a few changes to make this example different from
ch10 _ example21.html
. The first is in
the
handleDragStart()
function:
function handleDragStart(e) {
var data = {
elementId: this.id,
message: "You moved an element!"
};
The new code creates an object called
data
. It has an
elementId
property to contain the element's
id
value, and a
message
property that contains arbitrary text. You want to use this object as the drag and
drop's transfer data; so, you have to serialize it:
e.dataTransfer.setData("text", JSON.stringify(data));
}
You call the
JSON.stringify()
method to do just that, and the resulting JSON text is set as the
transfer's data.
The remaining changes appear in the
handleOverDrop()
function. Its first few lines are the same:
function handleOverDrop(e) {
e.preventDefault();
if (e.type != "drop") {
return;
}
But the next two lines are new:
var json = e.dataTransfer.getData("text");
var data = JSON.parse(json);
You retrieve the transferred data with the
getData()
method and store it in the
json
variable. You
then parse the JSON into a JavaScript object that you store in the
data
variable. You need to retrieve
the dragged element object from the document. So, you use
data.elementId
and pass it to
document
.getElementById()
:
var draggedEl = document.getElementById(data.elementId);
if (draggedEl.parentNode == this) {
this.className = "";
return;