- 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
Starting the Drag Operation
When the user starts dragging a draggable <div> element in our example, that <div> element's ondragstart event occurs, and we've tied that event to a JavaScript function named start().
In this task, we'll write the start() function to get the dragging operation started. That involves three steps: setting the allowed drag operation to "move" so the draggable <div> element that the user wants to drag may be dragged, storing the ID of the element that's being dragged so we can move it when it's dropped, and setting the image that the user will drag around.
To do all these things, follow these steps:
- Open draganddrop.html using a text editor such as Windows WordPad.
- Add the following code to the <head> section of dragdrop.html, starting a new <script> element, and creating the start() function:
<script type="text/javascript"> function start(e) { . . . }
- Add the following code to the start() function to indicate that the draggable <div> element the user is attempting to drag may indeed be moved (which you do by setting the dataTransfer.effectAllowed property of the event object passed to the start() function to "move"):
<script type="text/javascript"> function start(e) { e.dataTransfer.effectAllowed='move'; . . . }
- Add the following code to the start() function to store the ID of the <div> element being dragged so we can move it when it's dropped:
<script type="text/javascript"> function start(e) { e.dataTransfer.effectAllowed='move'; e.dataTransfer.setData("Data", e.target.getAttribute('id')); . . . }
- Add the following code to the start() function to set the drag image to the draggable <div> element, with an offset of (0, 0):
<script type="text/javascript"> function start(e) { e.dataTransfer.effectAllowed='move'; e.dataTransfer.setData("Data", e.target.getAttribute('id')); e.dataTransfer.setDragImage(e.target, 0, 0); return true; }
- 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 the user will be able to drag the draggable <div> elements in this example.