HTML and CSS Reference
In-Depth Information
Chapter 14
Drag and Drop
The ability to select an element and drag it to another location is an excellent example of a natural user
experience. I can still remember the early Apple computers where you could delete a file by dragging it onto a
trash can icon. This action, and hundreds more like it, are a key component of user experiences found on desktop
applications. Web applications, however, have lagged far behind in this arena. With the drag and drop (DnD) API
in HTML5, you'll find web applications rapidly catching up.
In this chapter you'll build a web application that implements a Checkers game, using the DnD API to move
the pieces around the board. I will first explain the concepts and how a DnD application is structured. Then
we'll dive into the code, demonstrating the various aspects. I'll finish up with some advanced features including
dragging between browser windows.
Understanding Drag and Drop
Before I get into building an application I want to explain the basic concepts of the DnD API. This will help
you put this in context as you start to write code. I will first explain the events that are raised; it is important to
know when each is raised and on which object. Then we'll look at the dataTransfer object, which you'll use to
pass information from the object being dragged to each of the events and eventually to the drop action. You can
also use this to configure various aspects of the dragging operation. Finally, I'll show you how to make objects
Handling Events
As with its desktop counterpart, DnD is an event-based API. As the user selects an item, moves it and drops it,
events are raised, allowing the application to control and respond to these actions. To effectively use this API,
you'll need to know when these events are raised and on which element they are raised. At first, this may seem
confusing but it's pretty straightforward once you see this in perspective.
In a DnD operation, there are two elements involved:
The element that is being dragged, sometimes referred to as the source
The element being dropped on, usually called the target
You can think of this as the source being an arrow that is being dropped onto a target, as illustrated in
Figure 14-1 .
Search WWH ::

Custom Search