Home > Software engineering >  Drag and drop when dragging one picture another picture is dropping
Drag and drop when dragging one picture another picture is dropping

Time:04-12

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

  <div >Akita Inu</div>
  <div >
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"><img id="drag1" src="corgi.jpeg" draggable="true" ondragstart="drag(event)" width="600" height="250"></div>
  </div>  
  
  <div >Cockapoo</div>
  <div >
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"><img id="drag1" src="akitainu.jpeg" draggable="true" ondragstart="drag(event)" width="600" height="250"></div>
  </div>

  <div >Corgi</div>
  <div >
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"><img id="drag1" src="cockapoo.jpeg" draggable="true" ondragstart="drag(event)" width="600" height="250"></div>
  </div>
  
  <div >Shiba Inu</div>
  <div >
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"></div>
  <div  ondrop="drop(event)" ondragover="allowDrop(event)"><img id="drag1" src="shibaInu.jpeg" draggable="true" ondragstart="drag(event)" width="600" height="250"></div>
  </div>

When I am dragging pictures to another divs it is always a Corgi picture appears for some reason. I tried using html5_draganddrop w3schools guide to make it but there is only one picture with two divs and I have multiple pictures and multiple divs and as I understand this guide doesn't work for me

CodePudding user response:

The problem in your code is that all of the images have the same id. To take this a step further, if you want to have a custom image show when dragging you can do the following.

In the dragstart event handler you want to add the drag image. The second and third parameters in the setDragImage function are X and Y offsets. You can view more information about this at: https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/setDragImage

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
    let img = new Image();
    img.src = 'https://www.somedomain.com/myimage.png';
    ev.dataTransfer.setDragImage(img, 10, 19);
} 
  • Related