Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Keep the original image after dropping it in another container

For example:

<script type="text/javascript">
  function allowDrop(ev) {
    ev.preventDefault();
  }

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

  function drop(ev) {
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
    ev.preventDefault();
  }
</script>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="x" src="X.png" draggable="true" ondragstart="drag(event)" width="75" height="75" />

I want to drag the x.png file and drop it into the div, but x.png will move into the div if I do so. How can I achieve that, after I drag and drop, the div gets a x.png, and the original x.png is still where it was?

like image 251
LFSQLANS Avatar asked Jan 27 '26 02:01

LFSQLANS


1 Answers

You can do that by duplicating the required DOM element by using cloneNode(true) method

<script type="text/javascript">
function allowDrop(ev) {
ev.preventDefault();
 }
function drag(ev) {
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev) {
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data).cloneNode(true));
ev.preventDefault();
}
</script>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="x" src="X.png" draggable="true" 
    ondragstart="drag(event)" width="75" height="75" />
like image 134
tkr_in Avatar answered Jan 29 '26 15:01

tkr_in