Home > Articles > Web Development > HTML/CSS

Dragging and Dropping with HTML5

  • Print
  • + Share This
Steven Holzner shows you how HTML5 supports drag-and-drop operations, a very popular part of HTML5.
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:

  • 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.

Figures 3.1

Figure 3.1 Denying a drag-and-drop operation.

Figures 3.2

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.

  • + Share This
  • 🔖 Save To Your Account