Jquery UI Draggable fix for scaled container

by gabfusi

HTML

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div class="wrap">

  <div id="container">
    <div class="draggable-element">Drag me!</div>
  </div>

</div>

CSS

#container{
  transform: scale(1.2);
  width: 300px;
  height: 200px;
  background: #000;
  position: relative;
  margin: 50px auto;
}

.draggable-element{
  background: #fff;
  color: #f00;
  position: absolute;
  width: 100px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  cursor: move;
}

JavaScript

var _zoom = 1.2,
    $element = $('.draggable-element'),
    $container = $('#container');

var containmentW,
    containmentH,
    objW,
    objH;

$element.draggable({

  start: function(evt, ui) {
    ui.position.left = 0;
    ui.position.top = 0;

    containmentW = $container.width() * _zoom;
    containmentH = $container.height() * _zoom;
    objW = $(this).outerWidth() * _zoom;
    objH = $(this).outerHeight() * _zoom;

  },

  drag: function(evt, ui) {

    var boundReached = false,

        changeLeft = ui.position.left - ui.originalPosition.left,
        newLeft = ui.originalPosition.left + changeLeft / _zoom,

        changeTop = ui.position.top - ui.originalPosition.top,
        newTop = ui.originalPosition.top + changeTop / _zoom;


    // right bound check
    if(ui.position.left > containmentW - objW) {
      newLeft = (containmentW - objW) / _zoom;
      boundReached = true;
    }

    // left bound check
    if(newLeft < 0) {
      newLeft = 0;
      boundReached = true;
    }

    // bottom bound check
    if(ui.position.top > containmentH - objH) {
      newTop = (containmentH - objH) / _zoom;
      boundReached = true;
    }

    // top bound check
    if(newTop < 0) {
      newTop = 0;
      boundReached = true;
    }

    // fix position
    ui.position.left = newLeft;
    ui.position.top = newTop;

    // inside bounds
    if(!boundReached) {

      // do stuff when element is dragged inside bounds

    }


  }
});