1

I'm using the HTML Drag/Drop API W3schools is suggesting (w3schools html drag/drop api)

I'm trying to make something like moving objects from 1 bag to another.

All is working fine so far except when I somehow misclick and drag 1 picture onto the other(instead into free space in the div).

Then the dropped picture is disappearing. When I check the html code, I can see that the dropped img went under the first img.

Probably because of the "child" element in the js code i guess. That is where I need help.

How do I prevent that so I can only drop the images into the divs but not into other images?

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, #div2 {
  float: left;
  width: 100px;
  height: 350px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<h2>Drag and Drop</h2>
<p>Drag the image back and forth between the two div elements.</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">Bag1
  <img src="https://www.w3schools.com/html/img_w3slogo.gif" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">Bag2
    <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" draggable="true" ondragstart="drag(event)" id="drag2" width="88" height="31">
</div>

</body>
</html>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
maryland
  • 21
  • 3

1 Answers1

1

just found the answer...

change the drop function to:

function drop(ev, el) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  el.appendChild(document.getElementById(data));
}

and when you call the function:

<div id="div1" ondrop="drop(event, this)" ondragover="allowDrop(event)">

thats it. found the answer here: prevent drop inside a child element when drag & dropping with JS

maryland
  • 21
  • 3