Machine Coding · Lesson 9 of 12 · 4 min
Drag & Drop Functionality (Basic)
This is a classic machine coding problem that tests your direct knowledge of the DOM event model and state management.
Drag and drop questions are not about fancy libraries. They are a direct probe into your understanding of browser events. The interviewer wants to see if you can manage state and manipulate the DOM using the platform's native APIs. Nail the event sequence and data transfer, and you've passed the test.
The Drag & Drop Event Sequence
The entire interaction is governed by a specific sequence of events fired on two different elements: the element being dragged and the potential drop target.
dragstart(on draggable): Fires once when the user begins dragging. This is your only chance to specify what data is being dragged.dragover(on target): Fires repeatedly as the dragged element is moved over a potential drop target. You must callevent.preventDefault()in this handler.drop(on target): Fires when the user releases the mouse over a valid target. This is where you read the dragged data and update the DOM.dragend(on draggable): Fires once when the operation finishes, whether it was successful (dropped) or not (cancelled). Use this for cleanup.
Other events like dragenter and dragleave are for styling, like adding a hover effect to a drop zone. They are useful but secondary to the main flow.
The trap: Forgetting event.preventDefault() in the dragover handler. By default, the browser prevents dropping on most elements. If you don't prevent this default behavior, the drop event will never fire. This is the single most common mistake candidates make.
How to Pass Data
You can't just pass an object reference. The drag operation is mediated by the browser, and data is passed via the DataTransfer object, which only holds strings.
In your dragstart event handler, use event.dataTransfer.setData(format, data).
formatis a string, typically a MIME type like'text/plain'or'application/json'. You can use a custom string.datamust be a string. To pass an object, you must serialize it first, for example withJSON.stringify().
In your drop handler, retrieve the data with event.dataTransfer.getData(format), using the same format string you used to set it. If you serialized an object, you'll need to parse it back with JSON.parse().
For simple cases like moving an element, just passing its ID is the most common and effective pattern.
A Standard Implementation
This is the minimum viable code for moving an element from one container to another. It covers the essential events and data transfer. In an interview, this is the foundation you'd build from.
// Assumes HTML with draggable items and a drop zone.
// <div id="item-1" draggable="true">...</div>
// <div id="drop-zone">...</div>
const draggable = document.getElementById('item-1');
const dropZone = document.getElementById('drop-zone');
// 1. On the draggable element
draggable.addEventListener('dragstart', (event: DragEvent) => {
// Store the ID of the element being dragged.
event.dataTransfer.setData('text/plain', (event.target as HTMLElement).id);
// Add a visual cue.
(event.target as HTMLElement).classList.add('dragging');
});
draggable.addEventListener('dragend', (event: DragEvent) => {
// Clean up the visual cue.
(event.target as HTMLElement).classList.remove('dragging');
});
// 2. On the drop zone
dropZone.addEventListener('dragover', (event: DragEvent) => {
// Allow the drop by preventing the default browser behavior.
event.preventDefault();
});
dropZone.addEventListener('drop', (event: DragEvent) => {
event.preventDefault();
// Retrieve the ID stored in dragstart.
const id = event.dataTransfer.getData('text/plain');
const element = document.getElementById(id);
if (element) {
// Append the dragged element to the drop zone.
(event.target as HTMLElement).appendChild(element);
}
});
Answering the "Build a Kanban Board" Prompt
This is a common framing for a drag-and-drop question. The interviewer is checking for a few specific things beyond just making it work.
Your goal is to demonstrate a clear, sequential implementation. Talk through your plan first:
- Make cards draggable.
- Set up
dragstartto store the card's ID.- Set up
dragoveron the columns to allow dropping.- Implement the
drophandler to move the DOM node.- Add visual feedback.
What they look for:
- Correct Event Handling: Do you know the key events (
dragstart,dragover,drop) and where to attach them? - The
preventDefault()Call: Did you remember it indragover? This is a pass/fail check. - Data Transfer: Are you correctly using
setDataandgetData? Passing the element ID is sufficient. - DOM Manipulation: You should be able to confidently find the element by its ID and append it to the new parent.
- Visual Feedback: A simple
.draggingclass that lowers opacity shows you're thinking about user experience. A.drag-overclass on the drop target is even better.
To stand out, mention accessibility. Native drag and drop is not keyboard accessible. A complete solution would require a parallel implementation using ARIA attributes and keyboard events (e.g., hitting Enter to "pick up" an item, using arrow keys, and hitting Enter again to "drop"). You won't be asked to code this in a 45-minute interview, but mentioning it shows seniority.
Try it
Implement a two-column board ("To Do" and "Done"). Create three draggable items in the "To Do" column. Write the JavaScript to allow them to be dragged and dropped into the "Done" column.
Next: Reusability Patterns: Hooks & HOCs
Lock it in — apply this lesson under interview conditions.