Javascript DOM Drop Event drag and drop elements between two drop targets

Description

Javascript DOM Drop Event drag and drop elements between two drop targets

View in separate window



<!DOCTYPE html>

<html lang="en">
<head>
<style>
[data-drop-target] {/*from w  w w.  j  a  v a  2 s  .com*/
  height: 400px;
  width: 200px;
  margin: 2px;
  background-color: gainsboro;
  float: left;
}

.drag-enter {
  border: 2px dashed #000;
}

.box {
  width: 200px;
  height: 200px;
}

.navy {
  background-color: navy;
}

.red {
  background-color: red;
}
</style>
</head>
<body>
  <div data-drop-target="true">
    <div id="box1" draggable="true" class="box navy"></div>
    <div id="box2" draggable="true" class="box red"></div>
  </div>
  <div data-drop-target="true"></div>

  <script>
    function handleDragStart(e) {
      e.dataTransfer.setData("text", this.id);
    }

    function handleDragEnterLeave(e) {
      if (e.type == "dragenter") {
        this.className = "drag-enter";
      } else {
        this.className = "";
      }
    }

    function handleOverDrop(e) {
      e.preventDefault();

      if (e.type != "drop") {
        return;
      }
      let draggedId = e.dataTransfer.getData("text");
      let draggedEl = document.getElementById(draggedId);

      if (draggedEl.parentNode == this) {
        return;
      }

      draggedEl.parentNode.removeChild(draggedEl);

      this.appendChild(draggedEl);
      this.className = "";
    }

    let draggable = document.querySelectorAll("[draggable]");
    let targets = document.querySelectorAll("[data-drop-target]");
    for (let i = 0; i < draggable.length; i++) {
      draggable[i].addEventListener("dragstart", handleDragStart);
    }

    for (i = 0; i < targets.length; i++) {
      targets[i].addEventListener("dragover", handleOverDrop);
      targets[i].addEventListener("drop", handleOverDrop);
      targets[i].addEventListener("dragenter", handleDragEnterLeave);
      targets[i].addEventListener("dragleave", handleDragEnterLeave);
    }
  </script>
</body>
</html>



PreviousNext

Related