2

I have a JavaScript drag and drop code,

I have two classes div1 for drop and div2 for drag.

I have set position of these two classes in CSS according to viewport width and height and is mandatory here.

The problem is, when I drag and drop div2 to div1, the element is not going and get placed inside div1.

How to make the class div2 dragged and get placed inside class div1?

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

  console.log(data);
  assignedTabName = document.getElementById(data).className;
  console.log(assignedTabName);

  ev.target.appendChild(document.getElementById(data));

}
.div1 {
  border: 2px solid black;
  position: absolute;
  width: 23vw;
  height: 10vh;
  left: 10vw;
  bottom: 80vh;
}

.div2 {
  border: 2px solid black;
  position: fixed;
  width: 14vw;
  height: 12vh;
  left: 0vw;
  bottom: 60vh;
  background-color: #FFFF00;
}
<div class="div1" id="drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div class="div2" id="drag1" draggable="true" ondragstart="drag(event)">
  <p width="336" height="69">hello</p>
</div>

1 Answer 1

2

I believe your positioning rules of the divs is the problem. If you remove the position: absolute from the CSS of .div1, and the position: relative from the CSS of .div2, then the drag-and-drop seems to work as expected.

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

  console.log(data);
  assignedTabName = document.getElementById(data).className;
  console.log(assignedTabName);

  ev.target.appendChild(document.getElementById(data));

}
.div1 {
  border: 2px solid black;
  width: 23vw;
  height: 10vh;
  left: 10vw;
  bottom: 80vh;
}

.div2 {
  border: 2px solid black;
  width: 14vw;
  height: 12vh;
  left: 0vw;
  bottom: 60vh;
  background-color: #FFFF00;
}
<div class="div1" id="drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div class="div2" id="drag1" draggable="true" ondragstart="drag(event)">
  <p width="336" height="69">hello</p>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.