sodcalculator

10 Tech How-To

Drag and Drop in JavaScript: A Step-by-Step Guide

Guide 10-48487 · Updated · Step by step

This guide walks you through implementing native HTML5 drag and drop in JavaScript, letting users click and drag elements to new positions or into drop zones. You’ll learn the essential events, how to transfer data, and how to style elements during the drag, with working code you can adapt to your own projects.

What You’ll Need

  • A modern web browser (Chrome, Firefox, Edge, or Safari) with HTML5 drag and drop support.
  • A text editor or IDE for writing the HTML, CSS, and JavaScript files.
  • Basic familiarity with HTML elements, CSS selectors, and JavaScript functions and event listeners.

Step-by-Step

  1. Create the HTML structure. Start with a container that holds the draggable items and a separate drop zone. For example, a list of items and a trash bin or a grid of cards. Give each draggable element the attribute draggable="true". This is the single most important attribute—without it, nothing will be draggable.
  2. Set up the CSS for visual feedback. Add styles for the default state, the element while it’s being dragged (e.g., reduced opacity or a dashed outline), and the drop zone when a drag is hovering over it. Use classes like .dragging and .drag-over that you’ll toggle with JavaScript.
  3. Select the elements in JavaScript. Use document.querySelectorAll() to grab all draggable items and document.querySelector() for the drop zone. Store them in variables so you can attach event listeners.
  4. Add the dragstart event listener. On each draggable item, listen for dragstart. In the handler, do two things: add the .dragging class to the element, and call e.dataTransfer.setData('text/plain', itemId) to store the item’s ID or other data. This data is what you’ll retrieve when the item is dropped.
  5. Add the dragend event listener. On the same draggable items, listen for dragend. In the handler, remove the .dragging class. This fires whether the drop was successful or not, so it’s the perfect place to clean up.
  6. Prevent default on the drop zone. On the drop zone, add a dragover event listener. The critical line here is e.preventDefault(). Without it, the browser will not allow a drop to happen. You can also add the .drag-over class in this handler to highlight the zone.
  7. Remove the highlight on dragleave. Add a dragleave listener on the drop zone to remove the .drag-over class when the dragged item leaves the zone. This prevents the highlight from staying on forever.
  8. Handle the drop event. Add a drop listener on the drop zone. In the handler, call e.preventDefault() again, retrieve the data with e.dataTransfer.getData('text/plain'), and then perform the actual move. For example, append the dragged element to the drop zone with dropZone.appendChild(document.getElementById(itemId)). Finally, remove the .drag-over class.
  9. Test and refine. Open the page in a browser and try dragging an item. If it doesn’t work, open the browser console to check for errors. You can also add console.log statements in each event handler to see which events are firing.

Common Mistakes

  • Forgetting the draggable="true" attribute. This is the most common mistake. Without it, the browser treats the element as static text or an image and won’t initiate a drag.
  • Not calling e.preventDefault() in dragover. If you skip this, the drop event will never fire. The browser’s default behavior is to reject the drop.
  • Using dragenter instead of dragover for the preventDefault. The dragenter event fires when the drag first enters the element, but dragover fires continuously while hovering. The drop is only allowed if you prevent default on dragover.
  • Not cleaning up the dragging class. If you forget to remove the .dragging class in dragend, the element will remain visually altered even after the drag ends.
  • Using setData with non-string data. The DataTransfer object only accepts strings. If you try to pass an object, it will be converted to “[object Object]”. Use JSON.stringify() if you need to pass complex data.

Tips

  • Use a unique ID for each draggable element. This makes it easy to identify and move the exact element when the drop happens. You can use the element’s index or a data attribute.
  • Add a visual cue like a placeholder. When dragging items in a list, it’s helpful to show where the item will be dropped. You can insert a temporary placeholder element at the drop position.
  • Consider touch devices. Native HTML5 drag and drop does not work on most touchscreens. For mobile support, you’ll need a library like SortableJS or implement touch events manually.
  • Style the drag image. By default, the browser shows a semi-transparent snapshot of the element. You can customize this with e.dataTransfer.setDragImage() in the dragstart event.
  • Use e.dataTransfer.effectAllowed and dropEffect. These properties let you control the cursor (copy, move, link) and communicate to the user what action will happen.

Troubleshooting

The drag doesn’t start at all. Check that the draggable="true" attribute is present on the element. Also, make sure you’re not trying to drag an element that is inside a form control or an iframe, which can interfere. Open the console for any JavaScript errors that might be preventing the event listeners from attaching.

The drop event never fires. The most likely cause is missing e.preventDefault() in the dragover handler. Double-check that the handler is attached to the correct drop zone and that it’s not being stopped by a parent element’s dragover handler.

The dragged element snaps back even though the drop seems to work. This happens when you don’t actually move the element in the drop handler. If you only log the data but don’t change the DOM, the browser will revert the drag. Make sure you append or insert the element into the drop zone.

The drop zone highlight flickers. This is usually because the dragleave event fires when moving over child elements of the drop zone. Use a counter to track the number of dragenter and dragleave events, and only remove the class when the counter reaches zero.

Data is undefined when dropped. Verify that you are using the same type string in setData and getData. For example, if you set ‘text/plain’, you must get ‘text/plain’. Also, ensure that the dragstart event is actually firing and setting the data before the drop.

Frequently Asked Questions

Can I drag elements between two different containers?

Yes. Attach the dragover and drop listeners to both containers. In the drop handler, you can check which container the element came from by looking at its parent, and then move it accordingly.

How do I make a list reorderable with drag and drop?

Add draggable="true" to each list item. In the dragover event on the list, use e.clientY to determine the mouse position and insert the dragged element before or after the item under the cursor using insertBefore().

Does drag and drop work on mobile devices?

Native HTML5 drag and drop is not supported on iOS Safari and has limited support on Android. For a consistent mobile experience, consider using a touch-compatible library or implementing touch events.

Can I drag files from my computer into the browser?

Yes. This is a different API but uses similar events. Listen for dragover and drop on a drop zone, and in the drop handler, access e.dataTransfer.files to get the file list.

How do I pass custom data like an object?

Use JSON.stringify() to convert the object to a string before calling setData, and then JSON.parse() after getData. This lets you pass any serializable data.

Is it possible to drag an element and drop it on itself?

Yes, it’s possible, but you’ll want to check in the drop handler whether the dragged element is the same as the drop target. If so, you can simply do nothing, preventing unnecessary DOM manipulation.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →