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?
offsetTop; distance = Math. sqrt(distX*distX + distY*distY); alert(Math. floor(distance));
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.
You can use Element. getClientRects() and Element. getBoundingClientRect() to get the size and position of an element.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With