Reputation: 62
I am trying to fix a problem with this drag-and-drop code. When I try to drag an image, that is not an 8, the 8 automatically goes up, and I am not able to drag any of the other images into the div box.
Also after dragging an image, if going into inspect mode in google, if you try to drag where the 8 was into the box that the images should go to, google gives a message saying:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at drop (Assignment10.html:41)
at HTMLDivElement.ondrop (Assignment10.html:50)
How do I fix this code?
I actually have not tried anything, because I do not have an idea on how to fix this code.
//JS for the drag-and-drop
function drag(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function permitDrop(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
}
#draginto {
width: 1520px;
height: 200px;
border-style: solid;
border-width: 1px;
}
#cards {
width: 64%;
}
#cards img {
float: right;
margin: 2px;
display: block;
}
!-- The box the images are dragged into--
<div id="draginto" ondragover="permitDrop(event)" ondrop="drop(event)">
</div>
!--The div with the cards in them--
<div id="cards">
<img src="https://via.placeholder.com/100x100?text=d8" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dJ" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dK" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=d10" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dQ" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=d9" draggable="true" id="dragto" ondragstart="drag(event)">
</div>
I expect for all the images to be able to be dragged into the box, and not just one.
Upvotes: 1
Views: 1492
Reputation: 31682
dragto
.event.target
is the #draginto
div, if so move the dragged item, otherwise do nothing:Like this:
function drop(event) {
let target = event.target;
if(target.id === "draginto") {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
target.appendChild(document.getElementById(data));
}
}
Upvotes: 1