Measure and calculate distance between two HTML elements' centers - Javascript DOM

Javascript examples for DOM:Element offsetHeight

Description

Measure and calculate distance between two HTML elements' centers

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*from  www  .j  a v  a2  s  .c o m*/
distX = y.offsetLeft - x.offsetLeft;
distY = y.offsetTop - x.offsetTop;
distance = Math.sqrt(distX*distX + distY*distY);
console.log(Math.floor(distance));
    }

      </script> 
   </head> 
   <body> 
      <div id="x"></div> 
      <br>
      <br> 
      <div id="y" style="margin-left:100px;"></div>  
   </body>
</html>

Related Tutorials