jQuery - Find distance between two DIVs

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
MarPlo
Posts: 90

jQuery - Find distance between two DIVs

I have two DIVs that I need to know the calculated browser distance (in width and height) of them.
Example html:

Code: Select all

<div id="dv1">div 1</div>
<div id="dv2">div 2</div>
I want to know the horizontal and vertical distances between these two (in pixels), using jQuery.

Admin
Use the offset() function.
Something like this should work:

Code: Select all

<div id="dv1">div 1</div>
Some text ...<br>
 https://coursesweb.net/
<div id="dv2">div 2</div>
<script>
var dist_ho = Math.abs($('#dv1').offset().left - $('#dv2').offset().left);  // horizontal distance
var dist_ve = Math.abs($('#dv1').offset().top - $('#dv2').offset().top);  // vertical distance

// test
alert('dist_ho: '+ dist_ho + ' - dist_ve: '+ dist_ve);
</script>
-The Math.abs() methods is used to have positive values.

Similar Topics