blue-sky
blue-sky

Reputation: 53806

Get position of div in relation to other divs

I have grid of divs 3 x 3

When i drag an item and it is dropped I would like to know the position of the dropped div in relation to all of the other divs.

Should I set an X,Y value on each div, and when it is dropped access the X,Y value of the div being moved ?

As showed in http://jsfiddle.net/adrianjsfiddlenetuser/8LQmE/ I would like to get the X,Y position of the div being dropped in relation to the other divs ?

Upvotes: 1

Views: 272

Answers (1)

Michael Slade
Michael Slade

Reputation: 13877

jQuery has a .offset() method that calculates and returns the pixel coordinates of the given element, relative to the document.

To get the position of one element relative to another, calculate the difference of the positions of the two elements:

var d1 = $("#div1");
var d2 = $("#div2");
var p1 = d1.offset();
var p2 = d2.offset();
var rel = { left: p2.left-p1.left, top: p2.top-p1.top };

Upvotes: 1

Related Questions