Drag&Drop HTML5/JS API Summary

gwagner's picture

Test the Drag & Drop Mechanism

Move me into the pink area (the drop zone).

The HTML specification defines an event-based drag-and-drop (D&D) mechanism, which is supported by all current major browsers (including IE11 and iOS/Safari), except on Android, according to caniuse. The main concepts of the HTML D&D mechanism are:

  1. A drag-and-drop operation is a complex user action composed of a drag user action performed on a source element (the "drag element") followed by a subsequent drop user action performed on a target element (the "drop zone").

  2. Using a pointing device (such as a mouse), a drag user action consists of a mousedown event on a drag element followed by a series of mousemove events, while the subsequent drop user action normally consists of the mouse being released on the drop zone element.

  3. When a browser detects a drag user action, it raises a dragstart event followed by a series of dragover events while the user keeps dragging the drag element.

  4. When a browser detects a drop user action, it raises a dragend event followed by a drop event.

A minimum setup for a D&D operation is obtained by taking the following steps:

  1. HTML elements can be made draggable by setting their draggable attribute to true. Image (img) and hyperlink (a) elements, as well as text selections, are draggable by default. The D&D API requires to transfer data (about the drag source element) by invoking an event handler for the dragstart event. So, we get the following HTML code:  

    <div id="drag" draggable="true" ondragstart="handleDragStart(event)">Drag me...</div>  
  2. When a draggable element is dragged somewhere, the D&D API requires to transfer data from the drag source element to the drop target element via the user interface events involved (mainly dragstart and drop). So, we need to define a JS function that handles the dragstart event such that a data item of the event's dataTransfer object is set:

    function handleDragStart( evt) {
      evt.dataTransfer.setData("text/plain", evt.target.id);
    }

    Notice that we create a dataTransfer item of type "text/plain" (normally, this should be a MIME type, but could also be a user-defined type keyword) with the drag element's id as its value.

  3. HTML elements can be turned into a drop zone for a D&D operation by invoking an event handler for the dragover event and another one for the drop event:

         <div id="dropZone" ondrop="handleDrop(event)" ondragover="handleDragOver(event)"></div>
       
  4. When a draggable element is dragged over an element where it is supposed to be dropped (the "drop zone"), the D&D API requires to prevent the browser's default behavior by invoking preventDefault in the JS function that handles the dragover event:

    function handleDragOver( evt) {
      evt.preventDefault();
    }   
  5. Finally, the drop event needs to be handled by making use of the transfered data items for achieving some effect. For instance, we can use the transferred id value of the drag element for positioning it within the drop zone element:

    function handleDrop( evt) {
      var dragElId = evt.dataTransfer.getData("text/plain"),
          dragEl = document.getElementById( dragElId),
          x = evt.clientX, y = evt.clientY;
      dragEl.style.position = "absolute";
      dragEl.style.left = x +"px";
      dragEl.style.top = y +"px";  
      evt.preventDefault();
    }

    Notice that the dataTransfer item type string (in our example "text/plain") is a key for retrieving the value of the data item.

The HTML D&D specification defines some unnecessarily complex features that seem to be simplified by browser implementations. For instance, it requires that the three events dragstartdragover and drop are cancelled (by invoking preventDefault in the respective JS event handler) for allowing to drag into a drop zone, but it turns out to be sufficient to do this for dragover and drop. The specification also defines a few additional features, which are, however, not that much important, like the dropEffect attribute for setting the drag shape (indicating either a move, a copy or a drag link operation).

For indicating to the user that an element is draggable, we set the cursor shape to a "move" symbol whenever the cursor is over a draggable element, using the following CSS code:

[draggable=true] {
    cursor: move;
}

The following code of the complete example also contains CSS style rules, e.g., for positioning and sizing the drop zone.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta charset="utf-8">
 <title>Test Drag&Drop</title>
 <meta name="viewport" content="width=device-width, initial-scale = 1.0" />
 <style>
  #drag {
      width: 100px;
      height: 100px;
      padding: 10px;
      background-color: deeppink;
      z-index: 1000;
  }
  [draggable=true] {
      cursor: move;
  }
  #dropZone {
      position: fixed;
      width: 100%;
      height: 100%;
      background-color: pink;
  }
 </style>
 <script>
  function handleDragStart( evt) {
    evt.dataTransfer.dropEffect = 'copy';
    evt.dataTransfer.setData("text/plain", evt.target.id);
  }
  function handleDragOver( evt) {
    // allow dropping by preventing the default behavior
    evt.preventDefault();
  }
  function handleDrop( evt) {
    var elId = evt.dataTransfer.getData("text/plain"),
        el = document.getElementById( elId),
        x = evt.clientX, y = evt.clientY;
    el.style.position = "absolute";
    el.style.left = x +"px";
    el.style.top = y +"px";
    el.textContent = "Moved to "+ x +"/"+ y;
    evt.preventDefault();
  }
 </script>
</head>
<body>
 <h1>Test Drag &amp; Drop</h1>
 <div id="drag" draggable="true" ondragstart="handleDragStart(event)">
  Move me into the pink area (the drop zone).
 </div>
 <div id="dropZone" ondrop="handleDrop(event)" ondragover="handleDragOver(event)"></div>
</body>
</html>

Category: