1

I have a simple html5 drag and drop.

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

Here's a demo: http://kod.djpw.cz/igob-

My problem is that I can drop multiple items in the same field. How can I prevent that? I'd like when I drop the item in the field, then there can't be no longer droped another item and when I drag the item out of the field, I'd like it to become dropable again.

Thanks for help.

user3529020
  • 86
  • 3
  • 13

1 Answers1

3

Only finish the drop if the field is empty solves the problem.

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    if (ev.target.childNodes.length === 0) {
        ev.target.appendChild(document.getElementById(data));
    }    
}
ctron
  • 684
  • 8
  • 15
  • 1
    That work's great, but you can no longer drop anything to the two fields where the two images started. How to prevent that? (edited demo: http://kod.djpw.cz/chob-) – user3529020 Jul 16 '15 at 11:15
  • Replace ev.target.childNodes.length with ev.target.children.length (The div tags with initial content have some text child nodes ... it is better to check for childrens so that only elements are returned) – ctron Jul 16 '15 at 13:59
  • I changed it and now I'm facing the same problem as at the begging. Now I can put multiple items in one field. – user3529020 Jul 17 '15 at 11:26
  • 1
    Yes, I have tried it the problem was that it is possible to drag the div with the image in the div with the other image instead of the circle so you must check that the element you drop to has the correct type change your if condition to (ev.target.children.length === 0 && ev.target.className === "souper") – ctron Jul 17 '15 at 11:55