Good afternoon, I'm doing a Drag and Drop code and dropping an image inside another image, it just adds
Good afternoon, I'm doing a Drag and Drop code and dropping an image inside another image, it just adds
The problem is here: ev.target.appendChild(copyimg);
When you are on top of an image the ev.target
is not the div#conteudo
but the image, and the image does not allow descendants so the .appendChild()
is stopped.
Pass this
in HTML ( ondrop="drop(event, this)"
) and then use div
directly as argument ( function drop(ev, div) {
).
The example would look like this:
//Drag'n Drop functions
var elementCounter = 0; // Designa a ID ao elemento dropado
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
ev.dataTransfer.effectAllowed = "copy";
}
function drop(ev, div) {
ev.preventDefault();
var x = ev.clientX;
var y = ev.clientY;
var data = ev.dataTransfer.getData("text");
var copyimg = document.createElement("img");
var original = document.getElementById(data);
copyimg.src = original.src;
div.appendChild(copyimg);
if (original.parentNode.id == "conteudo") {
original.parentNode.removeChild(original);
alert("Movendo imagem ");
copyimg.id = "dropped_elem" + (++elementCounter);
copyimg.setAttribute("style", "position: fixed; top: " + (y - 50) + "px; left:" + (x - 50) + "px;");
copyimg.setAttribute('draggable', true);
copyimg.setAttribute('ondragstart', "drag(event)");
} else {
alert("Nova imagem ");
copyimg.id = "dropped_elem" + (++elementCounter);
copyimg.setAttribute("style", "position: fixed; top: " + (y - 50) + "px; left:" + (x - 50) + "px;");
copyimg.setAttribute('draggable', true);
copyimg.setAttribute('ondragstart', "drag(event)");
}
}
#conteudo {
width: 250px;
height: 250px;
float: left;
background-color: #ff1;
display: initial;
margin: auto;
z-index: 6;
overflow: hidden;
}
<html>
<body>
<img id="drag1" width=50px height=50px src="https://orig00.deviantart.net/0772/f/2015/291/2/9/29820d36256689bdeae12f344e4f0b7a-d9djrwh.gif"draggable="true" ondragstart="drag(event)" alt="" />
<div id="conteudo" ondrop="drop(event, this)" ondragover="allowDrop(event)">
</div>
</body>
</html>