Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance (in px) between two elements in the DOM

Tags:

javascript

dom

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 .

like image 687
Hommer Smith Avatar asked Oct 29 '13 23:10

Hommer Smith


1 Answers

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);
like image 122
Cameron Askew Avatar answered Sep 25 '22 01:09

Cameron Askew