DEV Community

Cover image for HTML Drag and Drop API
Diego Cachafeiro for Product Hackers

Posted on • Edited on

HTML Drag and Drop API

The Drag and Drop API allows you to, as its own name indicates, to create drag and drop interfaces for the users to interact with.

This API will make available for the users to select elements you allow to with a click, and drag them to the droppable interfaces you also allow them to, this is all customizable you will be able to indicate which elements are draggables and where can be drop into as easy as with some simple functions with some basic functionalities.

I'll explain to you step by step how to do a simple drag and drop for text:

  • First you need to identify what will be draggable, this can be done by adding the draggable attribute and the ondragstart handler:
<script>
  function dragstart_handler(el) {
    el.dataTransfer.setData("text/plain", el.target.id);
  }

  window.addEventListener('DOMContentLoaded', () => {
    // Reference to the element we will drag
    const element = document.getElementById("draggable");
    // Add the handler to the div to make it draggable
    element.addEventListener("dragstart", dragstart_handler);
  });
</script>

<div id="draggable" draggable="true">You can drag this element.</div>
Enter fullscreen mode Exit fullscreen mode
  • After this you need to define what will the draggable object do when you drag it and drop it on the droppable zone, this will be done by creating a function with a dropEffect, there are three dropEffects:
    1. copy the dragged object will be copied on the droppable zone.
    2. move the dragged object will move to the droppable zone.
    3. link indicates that some form of relationship or connection will be created between the source and drop locations.

For my example I will use the move dropEffect as follows:

function dragover_handler(el) {
  el.preventDefault();
  el.dataTransfer.dropEffect = "move";
}
Enter fullscreen mode Exit fullscreen mode
  • For the last step we need to define a droppable zone, and the function linked to it, in this example we are moving the draggable object into de droppable zone:
<script>
function drop_handler(el) {
 el.preventDefault();
 const data = ev.dataTransfer.getData("text/plain");
 el.target.appendChild(document.getElementById(data));
}
</script>

<p id="target" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">Drop Zone</p>
Enter fullscreen mode Exit fullscreen mode

When we combine all the steps we will end up with a code like this codePen I created for you to test and see how its done, to test it you need to drag the text You can drag this element. into the text Drop zone for it to move.

To finish I will add that this is a little example on how can you use this API, there are many possibilities, for example you can also drag images, and drop them onto the droppable zone, not only text.

Top comments (0)