jfuyf
3/6/2018 - 10:14 AM

jQuery UI Draggable transform scale fix

jQuery UI Draggable transform scale fix

// see fiddle https://jsfiddle.net/gabfusi/femvbz4n/

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

    }

  }
});