Drag and Drop API
The HTML Drag and Drop API lets a user move data or an element to a drop target, but dragging should never be the only way to complete an action.
What you will learn
- How drag and drop events fit together
- How a drop target reads transferred data
- How to provide a keyboard-friendly alternative
Basic flow
source.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', source.id);
});
target.addEventListener('dragover', (event) => {
event.preventDefault();
});
target.addEventListener('drop', (event) => {
event.preventDefault();
const id = event.dataTransfer.getData('text/plain');
console.log('Dropped:', id);
});The drop target must cancel dragover to signal that it accepts a drop. Data is transferred through DataTransfer.
Accessibility and safety
- Provide buttons, menus, or another keyboard path for the same move.
- Show which target is active and make the result clear after dropping.
- Do not trust transferred strings; validate them before using them.
- Test touch devices because browser drag behavior may differ from a mouse.
Common mistakes
- Listening only for
dropwithout enabling the target ondragover. - Assuming a drag gesture exists for keyboard or touch users.
- Moving the DOM before checking that the source and target are valid.