Search code examples
javascriptimagefunctiondraggable

How to change an image by dragging another one towards it?


So I am trying to change picture A to picture B by dragging picture B over it. I got it working with just one picture, but I want it to work with multiple.This image kind of pictures what I want to do.

What I have so far in JS:

function movePlayer1() {
    if (document.getElementById("pack")) {
        document.getElementById("spot1").src = "image/" + playerImg1;
    } else {
        document.getElementById("spot1").src = "image/" + playerImg2;
    }
}
document.querySelectorAll("img#spot1")[0].addEventListener("dragover", movePlayer1);
I am new to Javascript, but I have tried multiple things and couldn't figure out how to do this, so I'm hoping someone can help me with this. If I need to give any extra information, please let me know!

(When I drag "playerImg2" over document.getElementById("pack"), it still changes to "playerImg1" instead of "playerImg2".)

Thanks.


Solution

  • Use a background image for your droppable areas,
    and play with the draggability of your images:

    const isClass = (cl, el) => el.classList.contains(cl);
    const on = (typ, el, cb) => el.addEventListener(typ, cb);
    let dragEl;
    
    on("dragover",  document, (e) => e.preventDefault() );
    on("dragend",   document, (e) => e.target.style.opacity = 1 );
    on("dragstart", document, (e) => {
      dragEl = e.target;
      e.target.style.opacity = 0;
    });
    on("drop", document, (e) => {
      e.preventDefault();
      if(isClass("dropArea", e.target)) {
        dragEl.remove();
        e.target.append( dragEl );
      }
    });
    .dropArea {
      display:inline-block; vertical-align:middle;
      width: 57px; height: 87px; margin: 8px;
      background: url('https://i.sstatic.net/5nsDs.png') no-repeat 50% 50% / cover;
    }
    .dropArea.small{
      width:  30px; height: 40px;
    }
    .dropArea img{
      width: 100%; height: 100%;
      transition: 0.3s;
    }
    <div class="dropArea"><img src="https://i.sstatic.net/sBQ1c.png" draggable="true"></div>
    <div class="dropArea"><img src="https://i.sstatic.net/kR6MI.png" draggable="true"></div>
    <div class="dropArea"><img src="https://i.sstatic.net/XSBBq.png" draggable="true"></div>
    <div class="dropArea small"></div>
    <div class="dropArea small"></div>
    <div class="dropArea small"></div>