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 ?
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>.