htmldomdragdrop

How do I access both the drag and drop element in HTML?


The 'dragenter' event fires when a dragged element enters a drop element. This event is attached to the drop element, so I can access that. Where is the dragged element?


Solution

  • As per the documentation one click away from the URL you referenced:

    You have to keep track of it, using the dragstart event, yourself.

    let dragged = null;
    
    const source = document.getElementById("draggable");
    source.addEventListener("dragstart", (event) => {
      // store a ref. on the dragged elem
      dragged = event.target;
    });
    
    const target = document.getElementById("droptarget");
    target.addEventListener("dragover", (event) => {
      // prevent default to allow drop
      event.preventDefault();
    });
    
    target.addEventListener("drop", (event) => {
      // prevent default action (open as link for some elements)
      event.preventDefault();
      // move dragged element to the selected drop target
      if (event.target.className === "dropzone") {
        dragged.parentNode.removeChild(dragged);
        event.target.appendChild(dragged);
      }
    });