Giox
Giox

Reputation: 5123

Resize of draggable elements with interactJs

I'm building a draggable element blocks that should be also resized. Both drag&drop and resize are only possible on the x-axis.

I've chosen interactJs as a support library to manage the drag&drop and the resize.

It's all fine on the drag&drop but when I've added also the resize, the movement is not any more linear, and if I resize the block and then move it, it slides on another x position.

Here is the js code:

var element = document.getElementById('block1'),
    x = 0, y = 0;

interact(element)
  .draggable({
    snap: {
      targets: [
        interact.createSnapGrid({ x: 30, y: 30 })
      ],
      range: Infinity,
      relativePoints: [ { x: 0, y: 0 } ]
    },
    inertia: true,
    restrict: {
      restriction: element.parentNode,
      elementRect: { top: 0, left: 0, bottom: 1, right: 1 },
      endOnly: true
    }
  })
  .on('dragmove', function (event) {    
  var target = event.target;
    x += event.dx;
    event.target.style.webkitTransform = event.target.style.transform = 'translate(' + x + 'px)';
    target.setAttribute('data-x', x);
  }).resizable({
    // resize from all edges and corners
    edges: { left: true, right: true, bottom: false, top: false },

    // keep the edges inside the parent
    restrictEdges: {
      outer: 'parent',
      endOnly: true,
    },

    // minimum size
    restrictSize: {
      min: { width: 100, height: 50 },
    },

    inertia: true,
  })
  .on('resizemove', function (event) {
    var target = event.target,
        x = (parseFloat(target.getAttribute('data-x')) || 0);

    // update the element's style
    target.style.width  = event.rect.width + 'px';

    // translate when resizing from top or left edges
    x += event.deltaRect.left;
    target.style.webkitTransform = target.style.transform = 'translate(' + x + 'px)';

    target.setAttribute('data-x', x);
    target.setAttribute('title', 'Size: ' + Math.round(event.rect.width) + 'x' + Math.round(event.rect.height));
  });

As you can see, every time the user performs a drop or a resize I save the x position in the data-x attribute, so I can retrieve in the other event.

Here is a fiddle: https://jsfiddle.net/9qrd5vgn/1/

In order to reproduce the issue try to move the block in the center, then apply a large resize, then move it again.

Upvotes: 0

Views: 1079

Answers (1)

Tarek Adra
Tarek Adra

Reputation: 510

change the x value to x = event.clientX - target.offsetWidth/2;

you get:

 .on('dragmove', function (event) {  
  var target = event.target;
    x = event.clientX - target.offsetWidth/2;
    event.target.style.webkitTransform = event.target.style.transform = 'translate(' + x + 'px)';
    target.setAttribute('data-x', x);
  })

check it out on fiddle: https://jsfiddle.net/adratarek/7dj4f25p/17/

adding css for smooth drag https://jsfiddle.net/adratarek/c10Lpavy/1/

Upvotes: 1

Related Questions