Callum Linington
Callum Linington

Reputation: 14417

AngularJS Directive dragging object how to remove Undesired Mouse Effect

Here is this plunk, some code in the mouse up event:

element.css({
    top: (y + 20) + 'px',
    left:  (x + 20) + 'px'
});

This offsets the position of the object by 20 px in both directions. But when you click on the object again to drag it, it jumps, then when you release it jumps again.

This is undesired. If I have created, effectively a snap to grid system. Everytime a user drops an object, when they pick it back up or pick up another object, I don't want this undesired behaviour of the object shooting across the screen.

Obviously the effect on the plunk isn't that big, however, it gets greatly exaggerated when you use this snap to grid system.

It's like this because I don't understand where all the values are coming from, so if someone can enlighten me that would be great and show me the path to solving my issue.

Upvotes: 0

Views: 63

Answers (1)

Shouvik
Shouvik

Reputation: 11720

What you are doing wrong is you are not updating the values of x and y based on the new newX and newY values you are computing.

function mouseup() {
          var newX = canvas.calcPos(columns, x, 20, 740);
          var newY = canvas.calcPos(rows, y, 10, 670);

          x = newX; //What you need to be doing
          y = newY;

          widget.css({
            left: newX + 'px',
            top: newY + 'px'
          });

          console.log(genCoord(x, y), genCoord(newX, newY));

          function genCoord(val1, val2){
            var res = '(' + val1 + ',' + val2 + ')';
            return res;
          }

          $document.off('mousemove', mousemove);
          $document.off('mouseup', mouseup);
        }

this should effectively remove the extra offset that is being induced by your global scope retained x and y.

here is the updated plunkr

Upvotes: 1

Related Questions