Skip to main content

Drag and Drop Example

HTML Drag and Drop interfaces enable applications to use drag-and-drop features in browsers. The user may select draggable elements with a mouse, drag those elements to a droppable element, and drop them by releasing the mouse button.

HTML drag-and-drop uses the DOM event model and drag events inherited from mouse events. A typical drag operation begins when a user selects a draggable element, drags the element to a droppable element, and then releases the dragged element.

During the drag operations, several event types are fired, and some events might fire many times, such as the drag and dragover events.

The Drag Events#

From the source element,

  • dragstart
  • drag
  • dragend

On the target element,

  • dragenter
  • dragover
  • dragleave
  • dragexit
  • drop

Note that dragstart and dragend events are not fired when dragging a file into the browser from the OS.

Exmaple 1 - with drag and drop from local file system.#

Step 1 - Make Element Draggable#

First you need to add the draggable attribute to the html element and set it to true. Then in the javascript we need to add a event listener to the draggable element to listen for the dragstart event.

<div class="movingElements">
<div class="box">
<img src="" draggable="true" ... />
<div class="box"></div>
<div class="box"></div>

Every event related to drag and drop comes is a DragEvent object, and it comes with a property called dataTransfer which holds the data being dragged.
So in the dragstart event we need to use the dataTransfer property to specify that data we are moving.

const sourcElement = document.querySelector(".image");
sourcElement.addEventListener("dragstart", dragstart);
function dragstart(e) {

Step 2 - The Drop Target#

Where can we drag elements to is the next thing we need to specify. As well as we can’t just drag and drop any element, the element must be valid drop target.
To make an element a drop target you need to listen to atleast the dragover and drop events.
For the dragover event we only prevent the defaults.

For the drag event we get the data for the source (moving element) and then append it to the target element.

const targetElement = document.querySelectorAll(".box");
targetElement.forEach((el) => {
el.addEventListener("dragover", dragOver);
el.addEventListener("drop", dragDrop);
function dragOver(e) {
function dragDrop(e) {
const data = e.dataTransfer.getData("text");;

Note that each handler calls preventDefault() to prevent additional event processing for this event (such as touch events or pointer events).

A Basic Exmaple 2#

Addition Resources#

Flavio Copes

Last updated on