Drag and drop HTML elements

Drag and drop images or any HTML element within a document

We saw the main principles of HTML5 drag and drop in the previous sections. There are other interesting uses that differ in the way we copy and paste things to/from the clipboard. The clipboard is accessed through the dataTransfer property of the different events:

  1. event.dataTransfer.setData(“Fruit”, event.target.dataset.value);
  2. var data = event.dataTransfer.getData(“Fruit”);

<IMG> elements are all draggable by default!

Normally, to make an element draggable, you must add the draggable=true attribute. <img> elements are an exception: they are draggable by default! The next example shows how to drag and drop an image from one location in the document to another.

Example: move images as an HTML subtree

Try this example (adapted from braincracking.org (in French)) in your browser below or play with it at CodePen:

Code from the example:

  1. <html lang=”en”>
  2. <head>
  3. <style>
  4.    .box {
  5.       border: silver solid;
  6.       width: 256px;
  7.       height: 128px;
  8.       margin: 10px;
  9.       padding: 5px;
  10.       float: left;
  11.    }
  12. </style>
  13.     function drag(target, evt) {
  14.         evt.dataTransfer.setData(“Text”, target.id);
  15.     }
  16.     function drop(target, evt) {
  17.         var id = evt.dataTransfer.getData(“Text”);
  18.         target.appendChild(document.getElementById(id));
  19.         // prevent default behavior
  20.         evt.preventDefault();
  21.     }
  22. </head>
  23. <body>
  24. Drag and drop browser images in a zone:<br/>
  25.    <img src=http://html5demo.braincracking.org/img/logos/chrome1.png&#8221; id=“cr”      
  26.         ondragstart=drag(this, event) alt=“Logo Chrome”>
  27.    <img src=http://html5demo.braincracking.org/img/logos/firefox1.png&#8221; id=“ff”
  28.         ondragstart=drag(this, event) alt=“Logo Firefox”>
  29.    <img src=http://html5demo.braincracking.org/img/logos/ie1.png&#8221; id=“ie”
  30.         ondragstart=drag(this, event) alt=“Logo IE”>
  31.    <img src=http://html5demo.braincracking.org/img/logos/opera1.png&#8221; id=“op”
  32.         ondragstart=drag(this, event) alt=“Logo Opera”>
  33.    <img src=http://html5demo.braincracking.org/img/logos/safari1.png&#8221; id=“sf”
  34.         ondragstart=drag(this, event) alt=“Logo Safari”><br/>
  35.    
     class=“box” ondragover=return false ondrop=drop(this, event)>
  36.         

    Good web browsers

  37.    
  •    
     class=“box” ondragover=return false ondrop=drop(this, event)>
  •         

    Bad web browsers

  •    
  • </body>
  • </html>