Why is my element not a node ? Drag and Drop

45 Views Asked by At

From a foreach I am creating a few p elements and putting them into a div. I want to be able to drag and drop them.

This is my script to deal with drag and drop

<!-- language: lang-js -->

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

This is my script to create my elements and add properties to them.

My lienClient list contains an array of object.

With lien.lien I am getting a string that I put into my p element on loop

<!-- language: lang-js -->

    lienClient.forEach((lien) => {
      var x = document.createElement("div");
      var y = document.createElement("p");
      var z = document.getElementById("liensUrlClientBody");

      x.setAttribute("ondrop", "drop(event)")
      x.setAttribute("ondragover", "allowDrop(event)")
      x.setAttribute("height", "550px")

      y.setAttribute("draggable", "true")
      y.setAttribute("ondragstart", "drag(event)")
      y.innerHTML = lien.lien

      x.appendChild(y)
      z.appendChild(x)
    })

My HTML Elements when my script loaded

I cannot drag my p element inside the div of the other p element.

Error in console when I try to drag one of my p element to my div element

I tried to check nodeType on my <p> elements which returns 1 : If the node is an element node, the nodeType property will return 1.

I tried draging my <p> element into another random div. Same problem

Can someone explain to me what I am missing with Node elemnts and Node ?

1

There are 1 best solutions below

1
chrwahl On

It looks like you forgot to give the <p> an ID. Instead of using the "on..." attributes you can just have an event listener for the entire list (div.card-body).

When you drop, make sure that the parent element is the <div>, not another <p>.

const cardbody = document.querySelector('div.card-body');

cardbody.addEventListener('dragstart', ev => {
  ev.dataTransfer.setData("text", ev.target.id);
});

cardbody.addEventListener('dragover', ev => {
  ev.preventDefault();
});

cardbody.addEventListener('drop', ev => {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  let div = ev.target.closest('div');
  div.appendChild(document.getElementById(data));
});
div.card-body {
  display: flex;
  align-content: stretch;
  gap: 1em;
}

div.card-body > div {
  min-height: 6em;
  background-color: gray;
  flex: 1;
}
<div class="card-body">
  <div height="550">
    <p draggable="true" id="id1">test.fr</p>
  </div>
  <div height="550">
    <p draggable="true" id="id2">testtest.com</p>
  </div>
</div>