JSFiddle - React, Tailwind, and code Playground

by Dawid Karwat

HTML

<div id="draggable" class="dragme">"Hello World!"</div>
<img src="https://lh4.googleusercontent.com/-8tqTFxi2ebU/Ufo4j_thf7I/AAAAAAAADFM/_ZBQctm9e8E/w270-h203-no/flower.jpg" alt="drag-and-drop image script" title="drag-and-drop image script" class="dragme">

CSS

.dragme {
      position:relative;
      width: 270px;
      height: 203px;
      cursor: move;
  }
  #draggable {
      background-color: #ccc;
      border: 1px solid #000;
  }

JavaScript

function startDrag(e) {
    targ = e.target;

    offsetX = e.clientX;
    offsetY = e.clientY;

    if (!targ.style.left) targ.style.left = '0px';
    if (!targ.style.top) targ.style.top = '0px';

    coordX = parseInt(targ.style.left);
    coordY = parseInt(targ.style.top);
    drag = true;

    document.onmousemove = dragging;
    return false;
}

function dragging(e) {
    if (!drag) return;
    targ.style.left = coordX + e.clientX - offsetX + 'px';
    targ.style.top = coordY + e.clientY - offsetY + 'px';
    return false;
}

function stopDrag() {
    drag = false;
}
document.onmousedown = startDrag;
document.onmouseup = stopDrag;