Drag and Drop eating images

Asked

Viewed 255 times

1

I have a drag-and-drop problem. I have two Ivs, one with images that will be played to another div that has 1 specific image that cannot be moved. But when I drop on an image (both specific and other) the image disappears, it is food. I ask for your help in solving this problem. Follow the codes>

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

1 answer

3


What happens is you’re making one .appendChild() image itself when dropping an image on the other, causing only the first image to be displayed, since the tag img does not allow internal content, unlike div's etc.

What you can do is check if the event target ondrop is an image or not. If it is an image, you do the .appendChild() in the div-father. Just take the .tagName and check that it is equal to IMG; if it is, add before the .appendChild() one .parentNode, who is the div-father.

Just put a if in function drop():

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));
   }
}
  • MY FRIEND THANK YOU VERY MUCH YOU JUST SAVED MY JOB!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.