After some more snooping, I found a JavaScript example on Dottoro that led me down the rabbit hole.
Quick Answer
The text can be grabbed with event.dataTransfer.getData("Text")
assuming that the browser supports dataTransfer objects. There are other restrictions as well -- such as a Webkit issue where getData
is always empty on dragstart
or dragover
(source).
(Fiddle)
Likewise, the dragged text can be modified by using event.dataTransfer.setData("Text", newText)
. (Fiddle)
In both samples above, "Text" is the format
of the dragged content we are retrieving/modifying. There are many options listed in the MDN documentation, but note that the available formats for a given "drag" can be found in the events.dataTransferTypes
array.
Details and Context
The following code explains how to use the dataTransfer object and some peculiarities:
//Modify the text when some specific text is dragged.
function changeDraggedText(event) {
if (event.dataTransfer) {
// Note: textData is empty here for Safari and Google Chrome :(
var textData = event.dataTransfer.getData("Text");
var newText = "..." //Modify the data being dragged BEFORE it is dropped.
event.dataTransfer.setData (format, newText);
}
}
//Access the text when the `drag` ends.
function getDraggedText(event) {
if (event.dataTransfer) {
var format = "Text";
var textData = event.dataTransfer.getData (format);
if (!textData) {
// ... There is no text being dragged.
} else {
// ... Do what you will with the textData.
}
} else {
// ... Some (less modern) browsers don't support dataTransfer objects.
}
// Use stopPropagation and cancelBubble to prevent the browser
// from performing the default `drop` action for this element.
if (event.stopPropagation) {
event.stopPropagation ();
} else {
event.cancelBubble = true;
}
return false;
}
Which can just be bound to the ondrop
and ondragstart
events as in the following HTML:
<div ondragstart="changeDraggedText(event)">
Dragging these contents causes the `ondragstart` event to be fired.
</div>
<div ondragenter="return false;"
ondragover="return false;"
ondrop="getDraggedText(event);">
And likewise, the `ondrop` event gets fired if I drop anything in here.
</div>
Caution: if you don't override the ondragover
and ondragenter
events, they will treat drags as the browser normally treats them; this means you can't drop text onto a non-input block (such as a <div>
).