This chapter is from the book

This chapter is from the book

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:

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.

TIP

Note that all the "on" attributes start with "ondrag" with one exception—ondrop, which occurs when you drop a dragged item. It's worth bearing in mind that this attribute is ondrop, not ondragdrop, or you're going to confuse some browsers, which will not run your code.

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.