Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 122 Β· Web APIs

Drag and Drop

Build drag and drop with HTML and JavaScript. Learn the draggable attribute, the drag events, dataTransfer, drop zones and how to accept dropped files.

Dragging things around feels natural: you move cards between columns on a task board, reorder a playlist or drop a photo onto an upload box. HTML has a built-in Drag and Drop API for exactly this. You mark elements as draggable, listen for a handful of events, and pass data from the thing being dragged to the place it lands.

The API has a reputation for being a little odd, mostly because of one rule that trips up nearly everyone (you will meet it in the "drop zones" section). Once you know it, building drag and drop takes only a few lines.

Making an element draggable

Some things are draggable by default: selected text, images and links. To make any other element draggable, add the draggable attribute with the value "true":

HTML
<div draggable="true">Drag me</div>

draggable is an enumerated attribute, not a boolean one, so you must write the value. draggable="false" turns dragging off, which is handy for images and links you don't want people to drag by accident. You can read more about it in Global Attributes.

The drag events

A drag operation fires events on two different elements: the source (the element being dragged) and the target (whatever is under the pointer).

Event Fires on When
dragstart source The user starts dragging
drag source Repeatedly while dragging
dragend source The drag finishes, whether it was dropped or canceled
dragenter target The dragged item enters an element
dragover target Repeatedly while the item is over an element (every few hundred milliseconds)
dragleave target The dragged item leaves an element
drop target The item is released over a valid drop target

In practice you need just four of them: dragstart to say what is being dragged, dragover to allow dropping, drop to handle the result, and often dragend to clean up.

Carrying data with dataTransfer

Every drag event has a dataTransfer property: a small container that travels with the drag. In dragstart, put data in; in drop, take it out. Data is stored as strings, labeled with a format (a MIME type):

JavaScript
source.addEventListener('dragstart', (event) => {
  event.dataTransfer.setData('text/plain', event.target.id);
});

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

Using text/plain has a nice side effect: if the user drags your element into a text editor or another app, the text you set is what arrives there.

Data is locked during the drag. For security, getData() returns an empty string in dragenter and dragover. The values only become readable in drop. During the drag you can still check which formats are present with event.dataTransfer.types.

Drop zones: the one rule to remember

By default, almost nothing on a page accepts a drop. To turn an element into a drop zone, you must cancel the dragover event by calling event.preventDefault(). If you forget, the drop event never fires, no matter how carefully you wrote its handler.

JavaScript
zone.addEventListener('dragover', (event) => {
  event.preventDefault(); // "Yes, you may drop here."
});

Here is everything put together: a tiny task board. Drag the cards between the two columns.

A drag-and-drop task board

A few details in that example are worth copying into your own projects:

  • Visual feedback. The dragging class fades the card being moved, and the over class highlights the column under the pointer. People need to see where an item will land.
  • The dragleave check. dragleave also fires when the pointer moves from the column onto one of its children. Checking column.contains(event.relatedTarget) avoids a flickering highlight.
  • dragend always fires, even if the drop was canceled with the Escape key, so it is the right place to undo temporary styles.

effectAllowed and dropEffect

These two properties control the little icon next to the pointer and tell the browser what kind of operation this is:

  • In dragstart, effectAllowed says what the source permits: "copy", "move", "link", combinations such as "copyMove", "all" or "none".
  • In dragover, dropEffect says what will happen if the user drops here: "copy", "move", "link" or "none".

If the two don't match, the browser shows a "not allowed" cursor and does not fire drop.

You can also replace the semi-transparent "ghost" image the browser draws with event.dataTransfer.setDragImage(element, x, y) inside dragstart.

Dropping files

When someone drags files from their desktop onto your page, the files arrive in event.dataTransfer.files, a list of File objects. Each one has a name, a size in bytes, a MIME type and a lastModified date. Nothing is uploaded: the files stay on the user's computer until your code decides what to do with them.

Try it: drag one or more images (or any other files) from your computer onto the box.

Drop files to preview them

Two things to note:

  • Prevent the default everywhere. If a file is dropped just outside your zone, the browser's default action is to open the file, which navigates away from your page. Canceling dragover and drop on the whole document stops that.
  • FileReader reads a file's contents. readAsDataURL() turns an image into a data: URL you can put straight into an <img src>. For text files, use readAsText().

Always pair a drop zone with a file input. Not everyone can drag (think of keyboard users, or many phones). Put an <input type="file" multiple> inside or next to the zone and send both paths to the same function. See Input Types for the file input.

Accessibility and touch screens

Drag and drop is a mouse-first interaction. Keyboard users cannot pick up an element with the Drag and Drop API at all, and support on touch screens varies between browsers and devices. So treat dragging as a shortcut, never as the only way to do something:

  • On a task board, give each card a "Move to…" menu or buttons.
  • For reordering, add "Move up" and "Move down" buttons, and announce changes with a live region (see ARIA Roles, States and Properties).
  • For uploads, keep the file input.
HTML
<li draggable="true">
  Water the plants
  <button type="button" aria-label="Move 'Water the plants' up">↑</button>
  <button type="button" aria-label="Move 'Water the plants' down">↓</button>
</li>

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. You wrote a drop handler for a box, but it never runs. What is the most likely cause?

    An element only becomes a drop target when its dragover event is canceled with preventDefault(). Drop targets don't need draggable.
  2. 2. Which is the correct way to make a <div> draggable?

    draggable is an enumerated attribute, so it needs an explicit value: "true" or "false".
  3. 3. In which event can you read the values stored with setData()?

    For security, the data is only readable in the drop event. During dragenter and dragover you can only see which formats are present.
  4. 4. Where do dropped files appear?

    Dropped files arrive as a list of File objects in dataTransfer.files. Nothing is uploaded until your code sends them somewhere.
  5. 5. Why should a file drop zone also include an <input type="file">?

    Drag and drop is a convenience. A file input works for everyone, including keyboard and screen-reader users.

Summary

  • Add draggable="true" to make an element draggable; the source fires dragstart, drag and dragend.
  • Store data in dragstart with dataTransfer.setData() and read it in drop with getData().
  • A drop zone must cancel dragover with preventDefault(), or drop never fires.
  • Use classes for visual feedback, and effectAllowed/dropEffect for the cursor.
  • Dropped files arrive in dataTransfer.files; read them with FileReader.
  • Always provide a keyboard-friendly alternative such as buttons or a file input.

Next lesson: Web Storage, where you save data in the browser so it is still there after a reload.