Drag and Drop eating images

1

I have a problem with a Drag and Drop. I have two divs, one where you have images that will be played to another div that has a specific image that can not be moved. But when I give Drop over an image (both in specific and in others) the image disappears, it is food. I ask your help to solve this problem. Here are the >

<body>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
        <img src="bloco0.png">
      </div>
      <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">
            <image id="5" class = "bloco" src="bloco1.png" draggable="true" ondragstart="drag(event)">
                <image id="6" class = "bloco" src="bloco2.png" draggable="true" ondragstart="drag(event)">
                    <image id="7" class = "bloco" src="bloco3.png" draggable="true" ondragstart="drag(event)">
                        <image id="8" class = "bloco" src="bloco4.png" draggable="true" ondragstart="drag(event)">
      </div>
<script type="text/javascript" src="js/main.js"></script>
<script>
        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));
        }
        </script>
</body>
    
asked by anonymous 25.11.2018 / 23:38

1 answer

1

What happens is that you are doing .appendChild() in the image itself by dropping one image over another, so that only the first one is displayed, since the img tag does not allow internal content, unlike div 's etc.

What you can do is check whether the target of the ondrop event is an image or not. If it's an image, you .appendChild() in the parent div. Just get the .tagName and check if it is equal to IMG ; if it is, add before .appendChild() a .parentNode , which is the parent div.

Just put a if in the drop() function:

function drop(ev) {
   ev.preventDefault();
   var data = ev.dataTransfer.getData("text");
   if(ev.target.tagName == "IMG"){
      ev.target.parentNode.appendChild(document.getElementById(data));
   }else{
      ev.target.appendChild(document.getElementById(data));
   }
}
    
26.11.2018 / 00:12