Django Johnson
Django Johnson

Reputation: 1449

distance jQuery UI draggable object has been moved, dragged

I am using the following code to allow for all members of the .dataCard class to be draggable left or right, but revert back to their original positions.

$('.dataCard').draggable({ axis: 'x', revert: true });

How can I tell the distance the item is away from its original position?

Upvotes: 2

Views: 3688

Answers (3)

sergio
sergio

Reputation: 1027

The actual math is trigonometry, and you need to calculate the distance, even if diagonal.

On start:

start_position = ui.position;

then on drag: which occurs in every mouse move, you calculate the distance like

if ( lineDistance( start_position , ui.position ) > 100 ) 
  {
    //do something here
  }

The function that does the magic is this:

function lineDistance( point1, point2)
{
  var xs = 0;
  var ys = 0;

  xs = point2.x - point1.x;
  xs = xs * xs;

  ys = point2.y - point1.y;
  ys = ys * ys;

  return Math.sqrt( xs + ys );
}

Upvotes: 0

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

Have made it across one axis only ..

drag: function (e, ui){
            y2 = ui.position.top;
            x2 = ui.position.left;
            if(y2>100){alert("greater");}
                    if(y2>100){alert("greater");}

        }

JSFIDDLE DEMO

Upvotes: 3

Dan-Nolan
Dan-Nolan

Reputation: 6657

You could use the left CSS property to determine how far it moved on the revert event:

revert: function() {
    alert($(this).css('left'));
    return true;
}

DEMO

Upvotes: 1

Related Questions