Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DataTransfer: allowed effects, drop effect, and drag data

The source sets which operations are allowed, the target selects one, and `setData()` stores the text the target can read on drop.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

// Source: write to this dragstart event's data store.
source.addEventListener("dragstart", (event) => {
  const transfer = event.dataTransfer;
  transfer.effectAllowed = "copyMove";
  transfer.setData("text/plain", "card-34");
});

// Target: accept a compatible drag using this dragover event.
target.addEventListener("dragover", (event) => {
  const transfer = event.dataTransfer;
  if (!transfer.types.includes("text/plain")) return;
  event.preventDefault();
  transfer.dropEffect = "copy";
});

// Target: read from this drop event's data store.
target.addEventListener("drop", (event) => {
  event.preventDefault();
  const text = event.dataTransfer.getData("text/plain");
});

DataTransfer.effectAllowed/dropEffect/setData covers two properties and one method on the object exposed as event.dataTransfer. This is a web platform API defined by HTML, not part of ECMAScript 2024. Check support in your target runtime.

Source: Set effectAllowed synchronously in dragstart. The values copy, move, and link allow copying, moving, or linking, respectively. copyLink, copyMove, and linkMove allow either of the named operations, all allows all three, and none allows no operation. The initial uninitialized also permits all three but can affect the default choice. Invalid values and writes outside read/write mode are ignored.

Target: In dragover, call preventDefault() if you accept the drag and set dropEffect to a permitted copy, move, or link. none means no operation; other values are ignored. The browser initializes this property for dragenter and dragover using the allowed effects and platform conventions, such as modifier keys. An incompatible choice does not enable a drop. In an accepted drop, call preventDefault() and implement the operation yourself: setting move does not move a DOM element.

Payload: setData(format, data) takes two strings and returns undefined. It adds text for a format or replaces existing text for that format. ASCII letters in the format are lowercased; text and url are aliases for text/plain and text/uri-list. If the store is not writable, the method makes no change.

Write text synchronously in dragstart. At the target, read it synchronously with getData() in drop, when the store is read-only. During dragover, inspect types instead of trying to read the payload. Keep the retrieved string, not the event object, for later use. Treat dropped data as untrusted and use textContent to display plain text.

Examples

(() => {
  const source = document.createElement("p");
  source.textContent = "Drag card-34";
  source.draggable = true;
  source.style.cursor = "grab";

  const target = document.createElement("div");
  const prompt = "Drop here";
  target.textContent = prompt;
  target.style.cssText = "border: 2px dashed; padding: 24px;";

  const format = "text/plain";
  source.addEventListener("dragstart", (event) => {
    event.dataTransfer.effectAllowed = "copy";
    event.dataTransfer.setData(format, "card-34");
  });

  function acceptCopy(event) {
    if (!event.dataTransfer.types.includes(format)) return;
    event.preventDefault();
    event.dataTransfer.dropEffect = "copy";
  }
  target.addEventListener("dragenter", acceptCopy);
  target.addEventListener("dragover", acceptCopy);

  target.addEventListener("drop", (event) => {
    event.preventDefault();
    const text = event.dataTransfer.getData(format);
    if (!text) return;
    target.textContent = text;
    console.log(`${event.dataTransfer.dropEffect}: ${text}`);
  });

  document.body.append(source, target);

  // Exercise the handlers once without mouse input. These synthetic events
  // share an explicitly created store; they do not start a native drag.
  const transfer = new DataTransfer();
  function dispatchDrag(element, type) {
    return element.dispatchEvent(new DragEvent(type, {
      bubbles: true,
      cancelable: true,
      dataTransfer: transfer,
    }));
  }

  if (!dispatchDrag(source, "dragstart")) return;
  dispatchDrag(target, "dragenter");
  const accepted = !dispatchDrag(target, "dragover");
  if (accepted && transfer.effectAllowed === "copy" && transfer.dropEffect === "copy") {
    dispatchDrag(target, "drop");
    target.textContent = prompt; // Reset the box for a native drag.
  }
})();

Result

copy: card-34

Run this in the browser console on a blank page. A synthetic drop logs `copy: card-34` and resets the box to “Drop here”. Then drag “Drag card-34” with a mouse onto the box. The box displays `card-34`, the source stays in place, and the console logs `copy: card-34` again.

Related lessons

  • JavaScript · Lesson 34 · Intermediate · Version: 3

Sources