amateur_coder
amateur_coder

Reputation: 62

How to fix drag-and-drop on multiple images?

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

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

  1. You have duplicate IDs. You can't have multiple elements with the same ID, otherwise only the first one get selected, hence you only able to move the 8 because it is the first element with the ID dragto.
  2. In the drop event handler you should check if 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

Related Questions