How do you keep a data array in sync with the DOM after drag and drop?
On dragend, read the DOM order: Array.from(list.children).map(li => li.textContent). Store this as the new data array. This keeps your data in sync with the visual order after reordering.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Build a Drag and Drop List in an Interview
Make items draggable=true. On dragstart, store the dragged index. On dragover, prevent default and reorder the DOM (insertBefore). On dragend, sync the data. Add CSS for visual feedback (opacity, cursor). Handle edge cases.
dragstart (drag begins), drag (during drag), dragenter (drag enters a target), dragover (drag over a target, must preventDefault to allow drop), dragleave (drag leaves a target), drop (item is dropped), dragend (drag ends).
Because by default, elements do not allow drops. preventDefault on dragover tells the browser that this element is a valid drop target. Without it, the drop event never fires.
Still have questions?
Browse all our FAQs or reach out to our support team
