How to implement drag and drop with the HTML5 Drag API

· Category: JavaScript

Short answer

Add the draggable="true" attribute to an element and handle events like dragstart, dragover, and drop. Call event.preventDefault() in dragover to allow dropping, and use event.dataTransfer to pass data between elements.

Details

The HTML5 Drag API uses a data transfer object to carry payload between the drag source and drop target. You can set multiple data formats with dataTransfer.setData(format, value) and customize the drag image with setDragImage(element, x, y). The API is synchronous and fires on the main thread, so heavy logic in dragover can cause jank.

For smoother custom drag experiences, many developers supplement the native API with pointer events. If you are handling complex event interactions, see How to debounce and throttle event handlers in JavaScript to keep performance high. For persisting reordered lists after a drop, you might use the Storage API to save layout state.

Tips

  • The native HTML5 drag API has limited touch support; consider a pointer-based polyfill for mobile.
  • Always provide keyboard-accessible alternatives for drag operations to meet accessibility requirements.
  • For related data manipulation, read about how to use array map filter reduce when reordering arrays after a drop event.