Search code examples
javascripthtmlcssdrag-and-drop

Unable to drag and drop an image over another image in JS?


I am writing a code in JS that performs drag and drop an image over another image. But I couldn't get the desired result. While dropping the image, it suddenly disappears. I've referred to the previous questions but couldn't find helpful. Someone help me understand the problem.

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));
}
<div class="col3 col-sm-12 col-md-4" id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <img src="https://picsum.photos/id/10/100/100" draggable="true" ondragstart="drag(event)" id="drag1">
</div>

<div class="col4 col-sm-12 col-md-4" id="div2" ondrop="drop(event)" ondragover="allowDrop(event)">   
  <img src="https://picsum.photos/id/1/100/100" alt="gown4">
</div>


Solution

  • The event.target return the highest element, which is the img element in your case. so what happen is that you append the dragged image into the second image, and not into the div, as expected.

    What you can do is pass the element to drop in as second parameter of the function, to make sure you drop into the wanted container and not some child element.

    Like so:

    function allowDrop(ev){
       ev.preventDefault();
    }
    function drag(ev){
       ev.dataTransfer.setData("text", ev.target.id);
       console.log(ev.target.id);
    }
    function drop(ev, el){
    console.log(ev);
       ev.preventDefault();
       var data = ev.dataTransfer.getData("text");
       el.appendChild(document.getElementById(data));
    }
    <div class="col3 col-sm-12 col-md-4" id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
      <img src="https://picsum.photos/id/10/100/100" draggable="true" ondragstart="drag(event)" id="drag1">
    </div>
    
    <div class="col4 col-sm-12 col-md-4" id="div2" ondrop="drop(event, this)" ondragover="allowDrop(event)">   
      <img src="https://picsum.photos/id/1/100/100" alt="gown4">
    </div>