fmalaussena fmalaussena - 1 month ago 8
HTML Question

Drag elements from one area to another

I'm trying to have two areas, one already populated with draggables that can be dragged to the other area.

Following the example at the bottom of this, I did the following :

<div class="well partis-in" ondrop="drop(event)" ondragover="allowDrop(event)">
<!-- Drag from here -->
<div class="label label-danger partis" draggable="true" ondragstart="drag(event)">PS</div><br>
<div class="label label-warning partis" draggable="true" ondragstart="drag(event)"> UDI</div><br>
<div class="label label-success partis" draggable="true" ondragstart="drag(event)"> EELV</div><br>
<div class="label label-info partis" draggable="true" ondragstart="drag(event)"> Les Républicains</div><br>
<div class="label label-default partis" draggable="true" ondragstart="drag(event)"> FN</div><br>
</div>

<div class="well partis-out" ondrop="drop(event)" ondragover="allowDrop(event)">
<!-- ...to here -->
</div>


And my javascript :

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));
}


But it's not working, it seems when you try to drag it, the mouse switches to the "I'm dragging something" cursor, but the labels are not dragged. Any idea why & how to make it work ?

To see it in (in)action, here is the codeply.

NB : once this is resolved, my next steps are :

1) making sure the elements can be ordered any way the user wants in the box on the right

2) when the user clicks on "Valider", the order of the elements in the box on the right will be sent to the backend.

If you think this won't be achievable with the code above, please do tell me.

Answer

All the parts are there, you are just missing the id attribute on each label. The problem is, you where trying to get the elements by "id" to append to the drop area, but your elements have no ids.

<div class="well partis-in" ondrop="drop(event)" ondragover="allowDrop(event)">
<!-- Drag from here -->
  <div id="id1" class="label label-danger partis" draggable="true" ondragstart="drag(event)">PS</div><br>
  <div id="id2" class="label label-warning partis" draggable="true" ondragstart="drag(event)"> UDI</div><br>
  <div id="id3" class="label label-success partis" draggable="true" ondragstart="drag(event)"> EELV</div><br>
  <div id="id4" class="label label-info partis" draggable="true" ondragstart="drag(event)"> Les Républicains</div><br>
  <div id="id5" class="label label-default partis" draggable="true" ondragstart="drag(event)"> FN</div><br>
</div>
Comments