Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript get distance bwetween elements

// 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);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #javascript #distance #bwetween #elements
ADD COMMENT
Topic
Name
4+6 =