Measure the distance between the two centers of the HTML elements

If I have HTML elements as follows:

<div id="x"></div> <div id="y" style="margin-left:100px;"></div> 

... how do I find the distance between them in pixels using JavaScript?

+11
javascript html distance
Jul 13 '13 at 8:38
source share
2 answers

Get your positions and use the Pythagorean theorem to determine the distance between them ...

 (function() { var getPositionAtCenter = function (element) { var data = element.getBoundingClientRect(); return { x: data.left + data.width / 2, y: data.top + data.height / 2 }; }; var getDistanceBetweenElements = function(a, b) { var aPosition = getPositionAtCenter(a); var bPosition = getPositionAtCenter(b); return Math.sqrt( Math.pow(aPosition.x - bPosition.x, 2) + Math.pow(aPosition.y - bPosition.y, 2) ); }; var distance = getDistanceBetweenElements(document.getElementById("x"), document.getElementById("y")); })(); 

jsFiddle .

Pythagorean theorem is related to the relation between the sides of a right triangle.

Pythagorean theorem

Elements are displayed on the Cartesian coordinate system (with the beginning in the upper left corner), so you can imagine a right triangle between (the unknown side is the hypotenuse).

You can modify the equation to get the value of c by getting the square root on the other side.

Distance equation

Then you simply paste the values โ€‹โ€‹into ( x and y are the differences between the elements after determining their centers), and you will find the length of the hypotenuse, which is the distance between the elements.

+22
Jul 13 '13 at 8:42 on
source share

since the div is now empty, the main idea is to measure the distance between their upper left corners

 distX = y.offsetLeft - x.offsetLeft; distY = y.offsetTop - x.offsetTop; distance = Math.sqrt(distX*distX + distY*distY); alert(Math.floor(distance)); 

but you have to subtract the first height and width of the div if you put something inside. This method has some problems with support and width of borders of elements in different browsers.

anyway take a look at fiddle

Note that even with content (unless you change it with css) divs will be 100% wide, so if you just want to measure br using height:

 distance = = y.offsetTop - x.offsetTop; 
0
Jul 13 '13 at 9:19
source share



All Articles