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?
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With