Tara Wilfred Tara Wilfred - 3 months ago 38
Javascript Question

Resize and Drag an Element using jsPlumb

I am working with the jsPlumb library to implement a simple interface where an element can be dragged from the toolbox and dropped onto the container. Here, I have an element('partitiondrop') that needs to be re-sizable and draggable at the same time. But, the following code doesn't permit the partition to be resized. Without the

jsPlumb.draggable
, the resize function works but once the element is dropped it can't be dragged.

drop: function (e, ui) {
var dropElem = ui.draggable.attr('class');
droppedElement = ui.helper.clone();
ui.helper.remove();
$(droppedElement).removeAttr("class");
$(droppedElement).draggable({containment: "container"});
jsPlumb.repaint(ui.helper);

var newAgent = $('<div>').attr('id', i).addClass('partitiondrop');
$(droppedElement).draggable({containment: "container"});

newAgent.css({
'top': e.pageY,
'left': e.pageX
});

$('#container').append(newAgent);

jsPlumb.draggable(newAgent, {
containment: 'parent'
});

$(newAgent).resizable({
resize : function(event, ui) {
jsPlumb.repaint(ui.helper);
}
});
}


CSS for partitiondrop

.partitiondrop {
border: 1px solid #346789;
resize: both;
overflow-x: hidden;
overflow-y: hidden;
...
z-index: 20;
position: absolute;
...
box-sizing: border-box;
}


Suggestions in this regard will be highly appreciated.

Answer

You can use the interact.js Javascript library for this. It provides an extensive function library specially methods to perform resizing and dragging at the same time.

interact('.resize-drag')
  .draggable({
    onmove: window.dragMoveListener
  })
  .resizable({
    preserveAspectRatio: true,
    edges: { left: true, right: true, bottom: true, top: true }
  })
  .on('resizemove', function (event) {
    var target = event.target,
        x = (parseFloat(target.getAttribute('data-x')) || 0),
        y = (parseFloat(target.getAttribute('data-y')) || 0);
// update the element's style
target.style.width  = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';

// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;

target.style.webkitTransform = target.style.transform =
    'translate(' + x + 'px,' + y + 'px)';

target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
target.textContent = Math.round(event.rect.width) + '×' + Math.round(event.rect.height);
});