HTML and CSS Reference
In-Depth Information
var drop = document.getElementById("dropzone");
drop.addEventListener("dragenter",dragenter,false);
drop.addEventListener("dragleave",dragleave,false);
drop.addEventListener("dragover",dragover,false);
drop.addEventListener("drop",drops,false);
Each of these events contains a new event property called dataTransfer. This property is
used to customize the drag and drop and to pass data from the drag element to the drop
element. It supports the following properties itself:
•
dropEffect
Indicates the type of drag and drop expected for the drop zone. If it
does not match the
effectAllowed
set in the drag element, then the drop will be
canceled. The options are
none
,
copy
,
link
, and
move
; for example:
e.dataTransfer.dropEffect = "copy";
•
effectAllowed
Indicates the types of drag and drop that the dragging element
will allow. If it does not match the
dropEffect
in the drop zone, then the drop will
be canceled. The options are
none
,
copy
,
copyLink
,
copyMove
,
link
,
linkMove
,
move
,
all
, and
uninitialized
; for example:
e.dataTransfer.effectAllowed = "move";
•
types
Presents a list of content types that the draggable data contains
:
if (e.dataTransfer.types.contains("text/html")){
//do something;
}
•
clearData()
Resets the data in the drag element.
e.dataTransfer.clearData();
•
setData(format,data)
Sets data to be sent to the drop zone. The format field
expects a string to indicate the format of the data being passed.
e.dataTransfer.setData("text/plain","Simple String");
e.dataTransfer.setData("text/html","<strong>HTML String</strong>");
•
getData(
format
)
Fetches the data set by the drag item. Only returns the data
that matches the format type.
e.dataTransfer.getData("text/html"); //returns <strong>HTML String</
strong>
•
setDragImage(
element
,
x
,
y
)
When an item is being dragged, it is possible for
the drag shadow to be set to any
element
. It can be an element on the page, an image,
a newly created element, or even a canvas drawing. The
x
,
y
coordinates indicate
where the mouse should attach to the shadow.
e.dataTransfer.setDragImage(document.getElementById("shadowimage",10,
10));
With the methods and properties exposed in the
dataTransfer
property, the drag
and drop is quite powerful. One exceptional feature is the ability to drag anything
into a drop zone and retrieve the content via
getData()
. This includes URLs from
the address bar, HTML from other pages, and text from Notepad documents.