Dragging and Dropping with HTML5
- 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
HTML5 supports drag-and-drop operations, where you can move elements and text around the browser window using a mouse or other pointing device.
That's useful for such operations as letting the user move items into a shopping cart, or letting them customize what elements appear in their home page, and it's a very popular part of HTML5.
Drag and drop is supported by a number of attributes added to HTML5 elements, such as the draggable attribute, which you set to true to make the element draggable. However, you do most of the work supporting drag and drop yourself, in a scripting language, such as JavaScript, as you'll see.
Let's jump into drag and drop operations immediately.
Welcome to Drag and Drop
From the point of view of HTML5 elements, drag and drop is pretty simple, involving these element attributes:
- Required attributes: draggable, ondragenter, ondragover, ondrop, ondragstart, ondragend
- Supported browsers: Chrome, Firefox, Opera, Safari
The real story takes place in scripting languages such as JavaScript, as you'll see. You connect each of the "on" attributes, such as ondragstart, to a JavaScript function like this for ondragstart, which occurs when the user starts dragging a draggable element:
ondragstart = "return start(event)";
It's up to you to write the code for the JavaScript function you connect to each of the "on" attributes.
In this lesson, we'll create the drag-and-drop example, draganddrop.html, you see in Figures 3.1 and 3.2. There are three <div> elements that you can drag around, labeled 1, 2, and 3. We've set up the example so that not all <div> elements can be dropped on the large square targets in the page. For example, if you try to drop <div> 1 onto the second target, you'll just get a "no" symbol, as shown in Figure 3.1, that indicates that target won't accept <div> 1. On the other hand, you can drop <div> 1 onto the third target, as shown in Figure 3.2.
Figure 3.1 Denying a drag-and-drop operation.
Figure 3.2 Allowing a drag-and-drop operation.
Now let's take a look at the draggable attribute and the "on" attributes and how you use them to support drag and drop.