␡
- 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
This chapter is from the book
Starting the Drag-and-Drop Example
To show how to put drag and drop to work, we're going to create an example named draganddrop.html, which you can see running in Figures 3.1 and 3.2, and whose code appears in its entirety at the end of this lesson.
To get started with the draganddrop.html example, follow these steps:
- Create draganddrop.html using a text editor such as Windows WordPad.
- Enter the following code to create the three targets onto which draggable elements can be dropped. Note that we will use <div> elements for the targets and that we connect the drag-and-drop events that targets support to JavaScript functions that we will write later.
<!DOCTYPE HTML> <html> <head> <title> Drag and Drop Example </title> </head> <body> <h1>Drag and Drop Example</h1> <div id="target1" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> </div> <div id="target2" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> </div> <div id="target3" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> </div> </body> </html>
- Add the following code to create the three draggable <div> elements as children of the first target. Note that we set each draggable <div> element's draggable attribute to true and also connect the events that draggables support to JavaScript functions, which we will write later.
<!DOCTYPE HTML> <html> <head> <title> Drag and Drop Example </title> </head> <body> <h1>Drag and Drop Example</h1> <div id="target1" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> <div id="draggable1" draggable="true" ondragstart="return start(event)" ondragend="return end(event)">1 </div> <div id="draggable2" draggable="true" ondragstart="return start(event)" ondragend="return end(event)">2 </div> <div id="draggable3" draggable="true" ondragstart="return start(event)" ondragend="return end(event)">3 </div> </div> <div id="target2" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> </div> <div id="target3" ondragenter="return enter(event)" ondragover="return over(event)" ondrop="return drop(event)"> </div> </body> </html>
- 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 we've got our example started with the three targets and three draggable elements. All that is invisible so far, however, so we will style them next.