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?
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.