3
Good afternoon, I’m making a Drag and Drop code and when dropping an image into another image, it simply disappears
In the example of this site the images are correctly one on top of the others
Already in my code (with images) when placing an image (²) on top of the other image (¹)... the image (²) some, can help me??
//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) {
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;
ev.target.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 {
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)");
console.log("Nova imagem ", elementCounter);
}
}
#conteudo {
width: 250px;
height: 250px;
float: left;
background-color: #ff1;
display: initial;
margin: auto;
z-index: 6;
overflow: hidden;
}
<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)" ondragover="allowDrop(event)">
</div>
Wooow!! Perfect !! Now I will study this part better to understand it well Just one more question, will have how to compare where the image will fall? For example, when I pull the image to the div, if it lands on the div, it will stand still And if it lands on another image, it will push it somewhere??
– Sora
The push part is the least, the problem is to compare where it will fall, whether it will fall into the div content or into an image
– Sora
@Sora does
console.log(ev.target.tagName);
and see if it’s a div or img.– Sergio
I am very grateful for your help!!! Valeuuu
– Sora