views:

39

answers:

2

I'm implementing jquery UI draggable and have 2 of these draggables that you see on the linked page. They're of course draggable, so I can move them around as needed.

How would I make them aware of each other though, so that I could try to make them align or show alignment marks when while being dragged, they get to the same x or y as another draggable?

+5  A: 

Sounds like a fun problem.

I think I would set a common reference point and measure their distance from each other by using that point to triangulate.

For example. You can use the top left of the page as a reference point... let elementa and elementb be the divs you're comparing. function getDistance(){ var aPos = $("#elementa").offset(); var bPos = $("#elementb").offset();

// distance of a to b:
//y = (y2-y1)
//x = (x2-x1)
var xa = aPos.left;
var xb = bPos.left;

var ya = aPos.top;
var yb = bPos.top;

//vector from point a to b:
x = xa-xb;
y = ya-yb;

// length of the vector (distance from div a to b)
return Math.sqrt(x*x + y*y);

}

if you want to get the position during drag you can either use a wrapper: http://jsbin.com/etako/edit

or log the position like: $(this).data('draggable').offset.click.top -= x

akellehe
I like the way you combine the X and Y offset into one metric. I will surely try this the next time I come across some position based checks.
jpluijmers
+3  A: 

Good question.

First you need to generate a list of the following data on each draggable:

  • The X position
  • The Y position
  • The Height
  • The Width

When defining objects as draggable you may bind a callback to the "drag" event. This event is triggered to fire if the draggable is moved 1 pixel. Meaning this callback will be called alot so it is key to keep calculations to a minimum.

When the callback is called you will get supplied with the ui and event objects. The ui object will contain valuable X and Y positioning data on the draggee.

With the dimensions and position of the draggee and the other draggables you can easely calculate the proximity to its sibblings and act accordingly. With the available data you should be able to implement akellehe's math.

Before I forget, you have to recalculate the position list on the draggable stop event.

Edit: check the following link on draggable it contains the documentation on the draggable events, methods and values.

jpluijmers