dbrree
dbrree

Reputation: 623

HTML5 Drag and Drop issue with Cloning and replacing

Thanks for taking a look into my issue. I have been trying to figure this out for days at this point, reading every possible HTML5 Drag and Drop reference there is as well as reading through as much as I could here on stackflow and I just can't figure out.

So onto my problem:

Source: https://jsfiddle.net/dzsk7311/3/

<div id="divLeft">
  <div id="divLeft1">
    <img src="http://icons.iconarchive.com/icons/designcontest/casino/96/Banana-icon.png" draggable="true" ondragstart="drag(event)" id="drag1" width="50" height="50">
  </div>
  <div id="divLeft2">
    <img src="http://icons.iconarchive.com/icons/rokey/smooth/128/apple-icon.png" draggable="true" ondragstart="drag(event)" id="drag2" width="50" height="50">
  </div>
</div>

<div id="divRight">
  <div id="divRight1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div id="divRight2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div id="divRight3" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div id="divRight4" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</div>

-

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 nodeCopy = document.getElementById(data).cloneNode(true);
   ev.target.appendChild(nodeCopy);
   ev.stopPropagation();
   return false;
}

What I want to accomplish:

What the problem is:

I hope this all makes sense, and I really appreciate any and all help since I have been racking my brain. I know that the code I have provided is limited, but I assure you, I have tried as many things as I possibly can think of and just wanted to go back to a good starting point for support.

Thank you all again.

Upvotes: 4

Views: 5221

Answers (1)

MaxZoom
MaxZoom

Reputation: 7763

I have modified your function slighlty to update node id

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var isLeft = 'drag1' == data || "drag2" == data;
  var nodeCopy = document.getElementById(data).cloneNode(true);
  nodeCopy.id = "img" + ev.target.id;
  if (!isLeft) {
    sourceNode = document.getElementById(data);
    sourceNode.parentNode.removeChild(sourceNode);
  }
  ev.target.appendChild(nodeCopy);
  ev.stopPropagation();
  return false;
}

See DEMO

Upvotes: 6

Related Questions