Game Development Reference
In-Depth Information
Drag-and-drop
Although creating drag-and-drop functionality manually is not a very challenging or-
deal, HTML5 takes drag-and-drop to a whole new level. With the new API, we're giv-
en the ability to do so much more than just let the browser handle the dragging and
dropping actions. The interface allows for customizing the exact way that things are
dragged, how the dragging action looks, what data is carried with the draggable ob-
ject, and so on. Plus, not having to worry about how the low level events are tracked
in different platforms and devices is a nice, welcome touch.
For the curious reader, the way we could implement our own drag-and-drop behavior
is really quite simple; first, we listen for a mouse down event on the element we want
to drag. When that happens, we set a mouse down flag, which we unset once the
mouse up event is fired, whether on the element we wish to drag or not. Next, we
listen for a mouse movement event, where we check if the mouse is down. If the
mouse is moving while the mouse down flag is set, we have a drag motion. One way
to handle it is to update the position of the draggable element every time the mouse
moves, then setting the element's position when the mouse up event is called. Of
course, there are several small details that we'd need to keep track of, or at least be
mindful of, such as how to detect where the draggable element was dropped, and
how to move it back to its original position if needed.
The good news is that the drag-and-drop API provided by the browser is very flexible,
and extremely efficient. Since this feature was first introduced, a lot of developers
continued to use JavaScript implementations of it for various reasons, but mostly be-
cause a lot of people felt that the native HTML5 version was a bit hard to use, buggy,
or not quite as practical as the version provided by whatever other library they chose
to use. However, today the API is widely supported, fairly polished, and highly recom-
mended.
How to use it
Now, the way that the drag-and-drop API works is very straight forward. First we need
to mark one or more elements as draggable by setting the draggable attribute to
true for those elements, as shown in the following code:
Search WWH ::




Custom Search