JSFiddle - React, Tailwind, and code Playground

by Twisty

HTML

<div id="canvas" data-zoom="0.5">
  <div class="dragme"></div>
  <div class="dragme"></div>
  <div class="dragme"></div>
</div>
<div id="report"></div>

CSS

#canvas {
  width: 800px;
  height: 650px;
  border: 1px solid #444;
  zoom: 0.5;
}

.dragme {
  width: 100px;
  height: 50px;
  background: #f30;
  margin-bottom: 10px;
}

JavaScript

var zoom = $("#canvas").data("zoom");
console.log(typeof zoom, zoom.toString());
var canvasHeight = $('#canvas').height();
var canvasWidth = $('#canvas').width();

$('#canvas').sortable({
  items: "div",
  start: function(e, ui) {
    console.log("Sort Start Triggered");
  },
  sort: function(evt, ui) {
    console.log("Sort Triggered");
    // zoom fix
    ui.position.top = Math.round(ui.position.top / zoom);
    ui.position.left = Math.round(ui.position.left / zoom);
    $("#report").html("Top: " + ui.position.top + " Left: " + ui.position.left);

    // don't let draggable to get outside of the canvas
    if (ui.position.left < 0) {
      ui.helper.css("left", 0);
    }
    if (ui.position.left + ui.helper.width() > canvasWidth) {
      ui.helper.css("left", (canvasWidth - ui.helper.width()) + "px");
    }
    if (ui.position.top < 0) {
      ui.helper.css("top", 0);
    }
    if (ui.position.top + ui.helper.height() > canvasHeight) {
      ui.helper.css("top", (canvasHeight - ui.helper.height()) + "px");
    }
    $("#report").html("Top: " + (canvasHeight - ui.helper.height()) + " Left: " + (canvasWidth - ui.helper.width()));
  }
});