Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure distance between two HTML elements' centers

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?

like image 939
tenstar Avatar asked Jul 13 '13 08:07

tenstar


People also ask

How do you find the distance between two elements in HTML?

offsetTop; distance = Math. sqrt(distX*distX + distY*distY); alert(Math. floor(distance));

How do you measure the distance between two objects?

To measure is to determine how far apart two geometric objects are. The most common way to measure distance is with a ruler. Inch-rulers are usually divided up by eighth-inch (or 0.125 in) segments. Centimeter rulers are divided up by tenth-centimeter (or 0.1 cm) segments.

How do you find the distance from the top of the window to the element?

You can use Element. getClientRects() and Element. getBoundingClientRect() to get the size and position of an element.


1 Answers

Get their positions, and use the Pythagorean Theorem to determine the distance between them...

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

If you browser doesn't support Math.hypot(), you can use instead:

Math.sqrt(   Math.pow(aPosition.x - bPosition.x, 2) +    Math.pow(aPosition.y - bPosition.y, 2)  ); 

The Pythagorean Theorem relates to the relationship between the sides of a right-angled triangle.

Pythagorean Theorem

The elements are plotted on a Cartesian coordinate system (with origin in top left), so you can imagine a right-angled triangle between the elements' coordinates (the unknown side is the hypotenuse).

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

Distance equation

Then, you simply plug the values in (the x and y are the differences between the elements once their centers are determined) and you will find the length of the hypotenuse, which is the distance between the elements.

like image 179
alex Avatar answered Sep 25 '22 23:09

alex