Javascript DOM Drag and Drop JSON

Description

Javascript DOM Drag and Drop JSON

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<style>
[data-drop-target] {/*from w w  w .  j  a v a2 s  .c  o m*/
  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) {
      let data = {
        elementId : this.id,
        message : "You moved an element!"
      };

      e.dataTransfer.setData("text", JSON.stringify(data));
    }

    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 json = e.dataTransfer.getData("text");
      let data = JSON.parse(json);

      let draggedEl = document.getElementById(data.elementId);

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

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

      console.log(data.message);
    }

    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