HTML and CSS Reference
Now that you understand the events that are used, you can implement a DnD operation by providing
appropriate handlers for each of these events.
Using the Data Transfer Object
There is one more DnD concept that you should understand as well. Simply dragging an element around a page
is not all that useful; what we're really after is the data associated with the element. In the example I gave earlier
with dragging a file to the trash can, seeing the icon swallowed up by the trash may be fun to watch, but the
ultimate goal is to delete the file. In this case, you're passing a file specification to the recycle bin so it can perform
the requested action in the file system.
In the DnD API, the dataTransfer object is used to store the data associated with the operation. The
dataTransfer object is usually initialized in the dragstart event handler. Recall that this event is raised on the
source element. The event handler can access the data from the source element and store it in the dataTransfer
object. This is then provided to all of the other event handlers so they can use it in their specific processing.
Ultimately, this is used by the drop event handler to take the appropriate action on this data.
The dataTransfer object is provided as a property of the event object that is passed to each of the event
handlers. You use the setData() method to store data in the dataTransfer object. To indicate the type of data, an
appropriate MIME type needs to be supplied as well. For example to add some simple text, call the method like this:
e.dataTransfer.setData("text/plain", "Hello, World!");
To access this data in a subsequent event, such as the drop event, use the getData() method like this:
var msg = e.dataTransfer.getData("text/plain");
You'll need to use the same MIME type when retrieving the data as was used when the data was stored.
Using Drop Effects
Another purpose for the dataTransfer object is to provide feedback to the user as to the action that will occur
when the item is dropped. This is called the drop effect and there are four possible values:
copy - the selected element will be copied in the target location
move - the selected element will be moved to the target location
link - a link to the selected item will be created in the target location
none - the drop operation is not allowed
When you start dragging an item, the cursor will change to indicate the drop effect that will occur when the
item is dropped on the target. This is standard Windows UI and you can try this out on most applications. For
example, using the text editor in Visual Studio, select some text and then start dragging it. You should see the
cursor change to either a move cursor or a “not allowed” cursor depending on where you trying to move it to. If
you hold down the Ctrl key before moving it, you should see the copy cursor instead of the move cursor.