Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get relative position between 2 DOM elements using JavaScript

I've implemented a set of draggable elements that can be dropped into some containers using jQuery. What I need is an animation that moves an element to a specific container without user interaction. The problem is that the elements and the drop containers are in completely different parts of the DOM and mostly positioned using float.

All I need is some code to get the absolute position difference between 2 floating DOM elements, preferrably using jQuery. The only thing I found were some hacks parsing upwards the DOM but always very browser-specific (e.g. "this does not work well with Firefox or IE or whatever").

Best would be something like this:

var distance = getDistance(element1, element2);

or in jQuery notation:

var distance = $(element1).distanceTo($(element2));
like image 377
davil Avatar asked Oct 22 '08 12:10

davil


2 Answers

I never used jQuery, just looked up API, so I can assume you can do the following:

var o1 = $(element1).offset();
var o2 = $(element2).offset();
var dx = o1.left - o2.left;
var dy = o1.top - o2.top;
var distance = Math.sqrt(dx * dx + dy * dy);
like image 62
Sergey Ilinsky Avatar answered Oct 10 '22 02:10

Sergey Ilinsky


What about the following?

var isIE = navigator.appName.indexOf("Microsoft") != -1;

function getDistance(obj1, obj2){
    var obj1 = document.getElementById(obj1);
    var obj2 = document.getElementById(obj2);
    var pos1 = getRelativePos(obj1);
    var pos2 = getRelativePos(obj2);
    var dx = pos1.offsetLeft - pos2.offsetLeft;
    var dy = pos1.offsetTop - pos2.offsetTop;
    return {x:dx, y:dy};
}
function getRelativePos(obj){
var pos = {offsetLeft:0,offsetTop:0};
while(obj!=null){
    pos.offsetLeft += obj.offsetLeft;
    pos.offsetTop += obj.offsetTop;
    obj = isIE ? obj.parentElement : obj.offsetParent;
}
return pos;
}
//
var obj = getDistance("element1","element2")
alert(obj.x+" | "+obj.y);
like image 30
Claudio Avatar answered Oct 10 '22 00:10

Claudio