Ad

Browser's Default Drag And Drop - How Should It Be Used With Selected Text?

I know that HTML5 provides drag and drop API, which make it easy to make elements drag-able. However, some elements are drag-able by default:

Within a web page, there are certain cases where a default drag behavior is used. These include text selections, images, and links. When an image or link is dragged, the URL of the image or link is set as the drag data, and a drag begins.

So, some elements - like selected text, does not require the draggable attribute in order to be drag-able. I couldn't find anything mentioned about it the w3c spec, so:

  1. How should I get this selected text data by using the default drag-and-drop behaviour?
  2. What the standard say about drag-able elements by nature? I wonder if I count on it to work the same on all modern browsers...
Ad

Answer

UPDATE: I've written a blog about this issue

It appears Drag-Able by default is even simpler, as they only require to pass the required data using dataTransfer. Attribute draggable is not required.

See snippets below or my more elaborated Codepen.

function allowDrop(ev) {
    ev.preventDefault();
}
  
function drag(ev) {
    const selection  = document.getSelection();
    ev.dataTransfer.setData('text:', selection.toString());
}

function drop(ev) {
    document.getElementById('drop').innerHTML = ev.dataTransfer.getData('text');
}
  div {
      padding: 20px;
      margin: 20px;
      border: 1px dashed gray
  }

  .drop-zone {
      border: 2px solid black
  }
<div id="drop" class="drop-zone" ondrop="drop(event)" ondragover="allowDrop(event)">
  Drop here
</div>

<div ondragstart="drag(event)">orem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

Ad
source: stackoverflow.com
Ad