- 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
Allowing Dragged Objects to Be Dropped on Certain Targets
When the user drags a draggable <div> element over a target, that target's ondragover event occurs, and we've tied that event to a function named over(). You can use the over() function to indicate whether the dragged item may be dropped on the current target. If you return a value of true from this function, the dragged item may not be dropped; returning a value of false means that it can be dropped.
To create the over() function, 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 over() function and getting the ID of the dragged item (iddraggable) and the ID of the target (id):
function over(e) { var iddraggable = e.dataTransfer.getData("Data"); var id = e.target.getAttribute('id'); . . . }
- Add the following code to the over() function to indicate that any dragged item may be dropped on target 1, that draggable <div> element 3 may be dropped on target 2 only, and that draggable <div> elements 1 and 2 may be dropped on target 3 only:
function over(e) { var iddraggable = e.dataTransfer.getData("Data"); var id = e.target.getAttribute('id'); if(id =='target1') return false; if((id =='target2') && iddraggable == 'draggable3') return false; else if(id =='target3' && (iddraggable == 'draggable1' || iddraggable =='draggable2')) return false; else 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 you've indicated to the browser which draggable <div> elements may be dropped on which target <div> elements.