Skip to content
Advertisement

How to Make This Drag n Droppable

I’m trying to make a form element drag and droppable, but I can’t make it work. Any ideas? I’m trying to make it be able to be dropped into another element.

Here is the code for the form element:

<div class="text1">
    <form>
        Item Name:<br>
        <input type="text" name="fname">
    </form>
</div>

Advertisement

Answer

The code below is based on the HTML5 Drag and Drop API. When you drop it into a box, it will execute a function that will drop it there.

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  /* not required, just shows hitboxes */
  border: 2px solid lime;
}

#div2 {
  width: 350px;
  height: 70px;
  padding: 10px;
  /* not required, just shows hitboxes */
  border: 2px solid magenta;
}

#drag1 {
  /* not required, just shows hitboxes */
  display: inline-block;
  border: 2px solid cyan;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div class="text1" id="drag1" draggable="true" ondragstart="drag(event)">
    <form>
        Item Name:<br>
        <input type="text" name="fname">
    </form>
</div>
<br>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

I added IDs because they are required for it to work.

This code adds two boxes that you can drag and drop an element into. It can also be dropped between pages.

Since a form input is also classified as something that can have stuff dropped into, I wouldn’t recommend drag and dropping a form with an input. You will get a hierarchy error if someone miss-clicks, and the DnD will refuse to work until you reload.

More information is on these pages: MDN webdev

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement