Eliminate "Ghosting" when Dragging an Image in the Browser

Ok - after fiddling with this some more, one sure-fire solution is to wrap the image inside a div element and drag the div element around. Check out this:

<!DOCTYPE html>
<html>

<head>
    <title>Drag Image Without Browser Ghosting</title>
    <style>
        #contentContainer {
          padding: 40;
        }
        #dragImage {
          width: 300px;
          height: 200px;
          background-color: blue;
          cursor: move;
          position: absolute;
        }
        #dragImage img {
          pointer-events: none;
          width: 300px;
          height: 200px;
        }
    </style>
</head>

<body>
    <div id="contentContainer">
      <div id="dragImage">
        <img src="https://www.kirupa.com/images/blueSquare.png"/>
      </div>
    </div>
    <script>
      var startDragging = false;

      var dragImage = document.querySelector("#dragImage");

      var elementX = 0;
      var elementY = 0;

      dragImage.addEventListener("mousedown", startDrag, false);
      dragImage.addEventListener("mouseup", stopDrag, false);
      dragImage.addEventListener("mousemove", drag, false);

      function startDrag(e) {
        startDragging = true;

        elementX = e.clientX - dragImage.offsetLeft;
        elementY = e.clientY - dragImage.offsetTop;

      }
      function stopDrag(e) {
        startDragging = false;
      }
      function drag(e) {
        if (startDragging) {
          var xPos = e.clientX - elementX;
          var yPos = e.clientY - elementY;
          dragImage.style.left = xPos + "px";
          dragImage.style.top = yPos + "px";
        }
      }
    </script>
</body>

</html>

Note that I set the pointer-events CSS property to none on our image element to ensure no mouse interactions affect it :slight_smile: