- Welcome to Drag and Drop
- Getting to Know the Drag-and-Drop API
- Starting the Drag-and-Drop Example
- Styling the Draggable and Target Elements
- Starting the Drag Operation
- Allowing Dragged Objects to Enter the Targets
- Allowing Dragged Objects to Be Dropped on Certain Targets
- Handling Drop Events
- Ending Drop Operations
- The draganddrop.html Example Code
Handling Drop Events
When the user drops a draggable <div> element on an allowed target <div> element, how do we move the draggable <div> to the target? That turns out to be simple—we'll just use the built-in JavaScript function appendChild to append the draggable <div> element to the current target <div> element.
When the user drops a draggable <div> element on a target, the ondrop event occurs in the target element, and we have connected a JavaScript function named drop() to implement the drop operation. To add drop() to the draganddrop.html example, follow these steps:
- Open draganddrop.html using a text editor such as Windows WordPad.
- Add the following code to the <script> section of dragdrop.html, creating the drop() function and getting the ID of the dragged item (iddraggable):
function drop(e) { var iddraggable = e.dataTransfer.getData("Data"); . . . }
- Add the following code to the drop() function to append the draggable <div> element to the target <div> element, as well as stopping further propagation of the event in the browser with the stopPropagation() function (returning a value of false also stops further propagation of the event):
function drop(e) { var iddraggable = e.dataTransfer.getData("Data"); e.target.appendChild (document.getElementById(iddraggable)); e.stopPropagation(); return false; }
- Save draganddrop.html. Make sure you save this code in text format (the default format for WordPad, for example, is RTF, rich-text format, which won't work with browsers).
Now you've handled the drop operation.