DataTransfer.getData()

This article needs a technical review. How you can help.

The DataTransfer.getData() method retrieves drag data (as a DOMString) for the specified type. If the drag operation does not include data, this method returns an empty string.

Example data types are text/plain and text/uri-list.

Syntax

DOMString dataTransfer.getData(format);

Arguments

format
A DOMString representing the type of data to retrieve.

Return value

DOMString
A DOMString representing the drag data for the specified format. If the drag operation has no data or the operation has no data for the specified format, this method returns an empty string.

Example

This example shows the use of the DataTransfer object's getData(), setData() and clearData() methods.

<!DOCTYPE html>
<html lang=en>
<title>Examples of DataTransfer.{setData(),getData(),clearData()</title>
<meta content="width=device-width">
<style>
  div {
    margin: 0em;
    padding: 2em;
  }
  #source {
    color: blue;
    border: 1px solid black;
  }
  #target {
    border: 1px solid black;
  }
</style>
<script>
function dragstart_handler(ev) {
 console.log("dragStart");
 // Change the source element's background color to signify drag has started
 ev.currentTarget.style.border = "dashed";
 // Set the drag's format and data. Use the event target's id for the data 
 ev.dataTransfer.setData("text/plain", ev.target.id);
}

function dragover_handler(ev) {
 console.log("dragOver");
 ev.preventDefault();
}

function drop_handler(ev) {
 console.log("Drop");
 ev.preventDefault();
 // Get the data, which is the id of the drop target
 var data = ev.dataTransfer.getData("text");
 ev.target.appendChild(document.getElementById(data));
 // Clear the drag data cache (for all formats/types)
 ev.dataTransfer.clearData();
}
</script>
<body>
<h1>Examples of <code>DataTransfer</code>: <code>setData()</code>, <code>getData()</code>, <code>clearData()</code></h1>
 <div>
   <p id="source" ondragstart="dragstart_handler(event);" draggable="true">
     Select this element, drag it to the Drop Zone and then release the selection to move the element.</p>
 </div>
 <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
</body>
</html>

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'getData()' in that specification.
Living Standard  
HTML5.1
The definition of 'getData()' in that specification.
Working Draft Initial definition

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 4 3.5 10 12 3.1
Feature Android Android Webview Chrome for Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support No support No support No support No support No support 10 No support No support

See also

Document Tags and Contributors

 Contributors to this page: rolfedh, Sebastianz, AFBarstow
 Last updated by: rolfedh,