I am attempting to do a simple drag and drop from one column to another. I am copying the element so that the list on the right can have multiple versions of the element on the left. Don't worry, I'm setting unique IDs before the actual append.
However I also want the user to be able to drag out of the box to delete that same object. But once the DIV is dropped into place (i.e. once it's in column2), it cannot be dragged again. The initial drag and drop works fine.
Solutions I've found deal with jQuery ui. I'm building an angularJS app and am not interesting in using full jQuery nor any additional plug-ins.
Help!
Sample code:
<div id="column1">
<div class="dragme" draggable="true" ondragstart="drag(event)">Item1</div>
<div class="dragme" draggable="true" ondragstart="drag(event)">Item1</div>
</div>
<div id="column2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<script>
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");
var newEl = $(document.getElementById(data)).clone()[0];
newEl.id = newEl.id + (+new Date());
ev.target.appendChild(newEl);
}
</script>
UPDATE
It seems that it's not the dragging and dropping that's causing the issue. Any dynamically added content won't drag. I tested this in the console.
FYI...The code below works just fine here, the problem ended up being that my drag/drop was within a draggable container.
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");
var origThing = document.getElementById(data);
var newThing = origThing.cloneNode(true);
ev.target.appendChild(newThing);
}
.thing {
width: 100px;
height: 2em;
padding: 0.5em;
margin: 0.5em;
background: rgba(0,0,0,0.8);
color: white;
font-family: sans-serif;
}
.col {
width: 130px;
height: 450px;
padding: 1em;
border: 1px solid;
border-radius: 5px;
position: relative;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="col" id="col1">
<div class="thing" draggable="true" ondragstart="drag(event)" id="thing1">THING 1</div>
<div class="thing" draggable="true" ondragstart="drag(event)" id="thing2">THING 2</div>
<div class="thing" draggable="true" ondragstart="drag(event)" id="thing3">THING 3</div>
<div class="thing" draggable="true" ondragstart="drag(event)" id="thing4">THING 4</div>
</div>
<div class="col" id="col2" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
ondragstartevent and less of the other thing in yourondragendevent. - Malk