How can I get the distance between two elements in the DOM?
I am thinking on using getBoundingClientRect, but I fail to see how can I use that in order to calculate the distance between two elements. So, for example, how close is a from an .
Pretend you have a div with id div1
and a div with id div2
. You could calculate the distance (in pixels) from div1
's center to div2
's center with some simple math...
// get the bounding rectangles
var div1rect = $("#div1")[0].getBoundingClientRect();
var div2rect = $("#div2")[0].getBoundingClientRect();
// get div1's center point
var div1x = div1rect.left + div1rect.width/2;
var div1y = div1rect.top + div1rect.height/2;
// get div2's center point
var div2x = div2rect.left + div2rect.width/2;
var div2y = div2rect.top + div2rect.height/2;
// calculate the distance using the Pythagorean Theorem (a^2 + b^2 = c^2)
var distanceSquared = Math.pow(div1x - div2x, 2) + Math.pow(div1y - div2y, 2);
var distance = Math.sqrt(distanceSquared);
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