Dragging and dropping multiple items

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 :innocent: This was going to be the first step towards being able to drag multiple items - so I can give the puppies a bone each :slight_smile:

Edit: The next stage was going to be to change querySelector to querySelectorAll and add a forEach.

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 :slight_smile:

Oh, der! Thanks.

1 Like

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.

Yes it would be easier I expect.

This isn’t meant to be an answer but it seems to work.

Hopefully a JS guru will drop by with some proper code :wink:

2 Likes

Thanks again, @PaulOB

I have found this article seems to answer some questions.

:slight_smile: