I'm trying to create a visual card counter. Basically images of cards that can be moved into different divisions.
I've started with code from https://www.w3schools.com/html/html5_draganddrop.asp
It works OK, but leaves me with one problem: If one image is dragged on top of another it disappears. Looking at the code, it seems to nest within the image it is dragged onto.
I've found several pages describing similar problems but not been able to get the proposed solutions working for me.
In short, I would like the dragged image to behave as if it had been dropped next to the static image; even if it is dropped on top by mistake.
Thanks in advance!
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
float: left;
width: 200px;
height: 335px;
margin: 10px;
padding: 10px;
border: 1px solid black;
background-color: aqua;
}
#div2, #div3 {
float: right;
width: 200px;
height: 335px;
margin: 10px;
padding: 10px;
border: 1px solid black;
background-color: rgba(255, 0, 0, 0.548);
}
</style>
<script>
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");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h2>Twilight Stuggle Card Tracker</h2>
<p>Drag the image back and forth between the two div elements.</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<h2>USA</h2>
<img src="imgeurope-scoring.jpg" draggable="true" ondragstart="drag(event)" id="drag1" width="90" height="126">
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="imgduck-and-cover.jpg" draggable="true" ondragstart="drag(event)" id="drag2" width="90" height="126">
</div>
<div id="div3" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="imgduckpix.GIF" draggable="true" ondragstart="drag(event)" id="drag3" width="190" height="28">
<img src="imgfive-year-plan.jpg" draggable="true" ondragstart="drag(event)" id="drag4" width="105" height="147">
</div>
</body>
</html>
When you drop an image directly over another image element, then ev.target will be that image. So go and check what element type you have in there, and if it is an image, go up to the parent element first.
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text"), target = ev.target;
if(target.nodeName == "IMG") {
target = target.parentNode;
}
target.appendChild(document.getElementById(data));
}