Ad

Make Multiple Elements Visible On Drop

- 1 answer

I have a code in which three image src with id drag1, drag2, drag3 each one can be dragged and dropped to div1..

My problem is, on dropping the second and third image it is not visible in #div1

How to make second and third image visible on drop?

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));

}
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="https://picsum.photos/200" draggable="true" ondragstart="drag(event)" width="336" height="69">
<img id="drag2" src="https://picsum.photos/200/300?image=0" draggable="true" ondragstart="drag(event)" width="336" height="69">
<img id="drag3" src="https://picsum.photos/200/300/?gravity=east" draggable="true" ondragstart="drag(event)" width="336" height="69">

Ad

Answer

Actually there's no problem with your actual code, and it's behaving the same way with the 3 images.

The problem is that your div has only 70px as height so only first image can be visible and the second two elements are inside the div but aren't displayed on screen, you can fix that by changing the div height or making it stretch with content.

Demo:

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));

}
#div1 {
  width: 350px;
  height: 370px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="https://picsum.photos/200" draggable="true" ondragstart="drag(event)" width="336" height="69">
<img id="drag2" src="https://picsum.photos/200/300?image=0" draggable="true" ondragstart="drag(event)" width="336" height="69">
<img id="drag3" src="https://picsum.photos/200/300/?gravity=east" draggable="true" ondragstart="drag(event)" width="336" height="69">

Ad
source: stackoverflow.com
Ad