Skip to content
Tutorials Center
My learning

Topics

Lesson 104 of 156 ยท Browser APIs

The Drag and Drop API

Build drag-and-drop interfaces with the HTML Drag and Drop API - draggable, dragstart, dragover, drop, dataTransfer, file drops, drag images and keyboard-friendly alternatives.

Moving a card between columns, reordering a playlist, dropping a photo onto an upload box: drag and drop feels natural to users, and browsers have a built-in API for it. You mark an element as draggable, listen for a handful of events, and carry information from the drag source to the drop target through a small object called dataTransfer. You do not need a library for the common cases.

This lesson walks through the events in the order they fire, shows the three rules that trip up almost every beginner, then builds a two-column board and a file drop zone. At the end you will see how to make drag and drop usable for people who cannot use a mouse.

Making an element draggable

Images, links and selected text are draggable already. For anything else, add the draggable="true" attribute:

HTML
<div class="card" draggable="true">Write the report</div>

That alone lets the user pick the element up, and a ghost image follows the pointer. To do something useful with it, you listen for events. Some fire on the dragged element, others on the element under the pointer:

Event Fires on When
dragstart the dragged element the drag begins
drag the dragged element continuously while dragging (rarely needed)
dragenter the element under the pointer the pointer enters a possible target
dragover the element under the pointer every few hundred milliseconds while over it
dragleave the element under the pointer the pointer leaves it
drop the element under the pointer the user releases the button over a valid target
dragend the dragged element the drag finishes, dropped or cancelled
sequenceDiagram
  participant S as Dragged element
  participant T as Drop target
  S->>S: dragstart (store data)
  T->>T: dragenter
  loop while over the target
    T->>T: dragover (preventDefault)
  end
  T->>T: drop (read data, update the page)
  S->>S: dragend (clean up)

A successful drag. If the pointer leaves the target, dragleave fires on it instead of drop.

The data store: dataTransfer

Every drag event has a dataTransfer property. It is the bag that travels with the drag. In dragstart you put something in it with setData(type, string); in drop you take it out with getData(type).

JavaScript
// Read-only
card.addEventListener("dragstart", (event) => {
  event.dataTransfer.setData("text/plain", card.id);
  event.dataTransfer.effectAllowed = "move";
});

column.addEventListener("drop", (event) => {
  event.preventDefault();
  const id = event.dataTransfer.getData("text/plain");
  column.append(document.getElementById(id));
});

Three details matter:

  • Data is stored as strings under a MIME-type key. Store an id (not the element), or use JSON.stringify() for several values. You can use your own type name such as application/x-card, but text/plain also makes the drop work when the user drags into another application, like a text editor.
  • You can only read the data in drop. During dragover the browser lets you see the types (dataTransfer.types) but hides the values, for privacy.
  • effectAllowed (set on the source) and dropEffect (set on the target) choose the cursor: "move", "copy", "link" or "none".

The three rules beginners miss

  1. You must call event.preventDefault() in dragover. By default the browser treats an element as not a drop target. Cancelling dragover is what says "dropping here is fine"; without it, drop never fires. This is the number one reason drag and drop "does nothing".
  2. Call event.preventDefault() in drop too. Otherwise the browser tries to handle the drop itself: it may navigate away and open a dropped file or a dropped link.
  3. dragleave fires when entering child elements. If you highlight a target on dragenter and remove the highlight on dragleave, the highlight flickers as the pointer crosses the target's children. Check event.relatedTarget, or use a small counter, or use the contains() test shown in the board below.

Build it: a two-column board

This board moves cards between two lists. Each card carries its id in dataTransfer; each column highlights while a card is over it and moves the card on drop. Because dragging is invisible to keyboard users, every card also has a button that moves it without dragging (more on that at the end of the lesson).

Drag cards between columns

Event delegation keeps the code short: one dragstart listener on the document serves every card, including cards you add later (see Event Delegation).

Custom drag images and effects

By default the ghost image is a translucent copy of the element. event.dataTransfer.setDragImage(element, offsetX, offsetY) replaces it with any element that is visible in the document (or an Image, or a canvas) when dragstart runs. It is useful when dragging a tiny handle should look like dragging the whole row. Combine it with effectAllowed = "copy" and a dropEffect of "copy" to show the "+" cursor for duplicating items instead of moving them.

Dropping files

Dragging files from the operating system onto a page uses the same events, but there is nothing to store in dragstart: the files already exist. In drop, read them from event.dataTransfer.files (a FileList), or from event.dataTransfer.items if you also want to tell files from dropped text. The File API methods are covered in Files and Blobs.

The demo below is a drop zone that lists what lands on it. You can try it for real by dragging any file from your computer onto the box. The button builds a fake drop with a DataTransfer object of your own, so the example also runs when you have no file at hand.

A file drop zone

Notice textContent for the file names: a file name is user-controlled text, so never put it into innerHTML (see XSS, CSRF and Safe DOM Updates). In real code, also check file.type and file.size before using a file, as in File Uploads and Progress.

Making drag and drop accessible

The native Drag and Drop API has real limits you should plan for:

  • Keyboards and screen readers. A drag needs a pointer. Always offer another way to do the same job: a "Move to..." button, a select box, or arrow-key reordering. The board above does this with its Move buttons.
  • Touch screens. Support for dragging with a finger is inconsistent across browsers and often conflicts with scrolling. If touch matters, test on real devices, or use pointer events to build the interaction yourself, or reach for a library built on them.
  • Announce changes. After a move, update a role="status" element ("Review the quiz moved to done"), as the board does.
  • Show where things can go. Highlight valid targets and use dropEffect so the cursor says whether a drop will work.

For simple lists, libraries such as SortableJS handle reordering, touch and animation, and they are built on top of exactly the events you just learned.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A drop target never receives the drop event. What is the most likely cause?

    An element only becomes a valid drop target when its dragover event is cancelled. The draggable attribute belongs on the element being dragged, not on the target.
  2. 2. When can you read the actual value stored with dataTransfer.getData()?

    For privacy, browsers hide the values until the user drops. During the drag you can inspect dataTransfer.types, but getData() returns an empty string.
  3. 3. Why do highlight effects often flicker when you remove them in dragleave?

    Moving over a child counts as leaving the parent, so dragleave fires. Check event.relatedTarget or use contains() so the highlight stays while the pointer is still inside the target.
  4. 4. Where do you find the files when a user drops them from the desktop?

    Dropped files are exposed as a FileList on event.dataTransfer.files (or through dataTransfer.items).
  5. 5. Which is the best way to make a drag-and-drop board usable for keyboard users?

    Native dragging needs a pointer. Offer a parallel way to perform the same action and announce it with a status message.

Summary

  • Add draggable="true" to make an element draggable. The events dragstart, dragenter, dragover, dragleave, drop and dragend describe the drag.
  • Carry data in event.dataTransfer with setData() in dragstart and getData() in drop. Store ids or JSON strings, never elements.
  • Call preventDefault() in dragover (to allow drops) and in drop (to stop the browser's own handling).
  • Dropped files arrive in event.dataTransfer.files; treat file names as untrusted text.
  • Use relatedTarget or contains() to avoid dragleave flicker, and effectAllowed/dropEffect to set the cursor.
  • Always provide a keyboard alternative and announce results; test touch devices separately.

Next, look at the APIs that need the user's permission before they work: Geolocation, Notifications and Clipboard APIs.