JavaScript: using native drag and drop

JavaScript: using native drag and drop

Native drag and drop is a feature recently made available in JavaScript on all browsers.

Native drag and drop is a feature recently made available in JavaScript on all browsers.

In order to use this feature, an element must be declared as draggable using the corresponding HTML5 attribute.


<div id="test" draggable="true">Drag me</div>
<div id="drop"></div>

We want to allow the addition of multiple copies of the original element within the element that follows it. The simplest solution is to create each time a copy of the item by cloning its contents.

We need to use three specific drag and drop events:

  1. dragstart: the element begins to be dragged.
  2. dragover: the item is on the target item.
  3. drop: the element is released in the target element.

How do we copy the contents of the original element from one event to another? Using the API of the event.dataTransfer object, by which it is possible to temporarily save different types of data in a dedicated event storage.


const draggable = document.querySelector('#test');
    const droppable = document.querySelector( '#drop');

    draggable.addEventListener('dragstart', e => {
        const dt = e.dataTransfer;
        const target = e.target;
        dt.setData('text/plain', target.innerText);
    });
    droppable.addEventListener('dragover', e => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
    });
    droppable.addEventListener('drop', e => {
        e.preventDefault();
        const dt = e.dataTransfer;
        const text = dt.getData('text/plain');
        const el = document.createElement('div');
        el.className = 'droppable';
        el.innerHTML = text;
        droppable.appendChild(el);
    });
 

Recall that event.target refers to the element to which the event was linked. The preventDefault() method is used here to prevent the browser from applying its default behavior when dragging and dropping the item.

You can see thee above code in action on the following page.