I have a simple drag and drop app on a codepen at https://codepen.io/gandalf458/pen/pogWdRx
It works fine, but if I change id="drag1"
to class="drag1"
in the HTML and #drag1
to .drag1
in the JS it stops working and I get an error: Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.
It seemed like such an innocent change This was going to be the first step towards being able to drag multiple items - so I can give the puppies a bone each
Edit: The next stage was going to be to change querySelector
to querySelectorAll
and add a forEach
.
PaulOB
June 30, 2020, 12:24pm
2
Blind leading the blind here but there seems to be 3 references to an id in that code.
document.querySelector(“#drag1 ”)
and
event.target.id)
and
document.getElementById(data))
I would assume it needs to be something like this:
document.querySelector(".drag1").addEventListener("dragstart", function () {
event.dataTransfer.setData("text", event.target.className);
});
document.querySelectorAll(".droparea").forEach(function (el) {
el.addEventListener("dragover", function () {
event.preventDefault();
});
el.addEventListener("drop", function () {
event.preventDefault();
const data = event.dataTransfer.getData("text");
event.target.appendChild(document.querySelector('.' + data));
});
});
(Of course that still only caters for one item but should identify problem areas for you).
However someone who knows what they are doing should be along shortly to rectify
Yeah, that works a treat, thanks squire.
I’m wondering if indeed I need id’s (or at least unique class names) for the draggable bones.
PaulOB
June 30, 2020, 2:30pm
5
Yes it would be easier I expect.
This isn’t meant to be an answer but it seems to work.
https://codepen.io/paulobrien/pen/WNrXvwr
Hopefully a JS guru will drop by with some proper code
2 Likes
Thanks again, @PaulOB
I have found this article seems to answer some questions.
Gandalf
Closed
October 6, 2020, 1:38pm
8
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.